Here You will get ,all you should know about C language,From knowledge and Interview Perspective
This is complete and enough for you to clear any exam or interview.
Most Common C Programming Interview Questions and Answers
Here we go.
Q #1) What are the key features in the C programming language?
Ans)
- Portability – Platform dependent language.
- Modularity – Possibility to break down large programs into small modules.
- Flexibility – The possibility to a programmer to control the language.
- Speed – C comes with support for system programming and hence it is compiling and executes with high speed when compared with other high-level languages.
- Extensibility – Possibility to add new features by the programmer.
Q #2) What are the basic data types associated with C?
Ans)
- Int – Represent the number (integer)
- Float – Number with a fraction part.
- Double – Double-precision floating-point value
- Char – Single character
- Void – Special purpose type without any value.
Q #3) What is the description for syntax errors?
Ans) The mistakes when creating a program called syntax errors. Misspelled commands or incorrect case commands, an incorrect number of parameters when called a method /function, data type mismatches can identify as common examples for syntax errors.
Q #4) What is the process to create increment and decrement stamen in C?
Ans) There are two possible methods to perform this task.
1) Use increment (++) and decrement (-) operator.
Example When x=4, x++ returns 5 and x- returns 3.
2) Use conventional + or – sign.
When x=4, use x+1 to get 5 and x-1 to get 3.
Q #5) What are reserved words with a programming language?
Ans) The words that are part of the slandered C language library are called reserved words. Those reserved words have special meaning and it is not possible to use them for any activity other than its intended functionality.
Example void, return int.
Q #6) What is the explanation for the dangling pointer in C?
Ans) When there is a pointer pointing to a memory address of any variable, but after some time the variable was deleted from the memory location while keeping the pointer pointing to that location. Following are examples.
// EXAMPLE 1
int
* ptr = (
int
*)
malloc
(
sizeof
(
int
));
..........................
free
(ptr);
// ptr is a dangling pointer now and operations like following are invalid
*ptr = 10;
// or printf("%d", *ptr);
// EXAMPLE 2
int
* ptr = NULL
{
int
x = 10;
ptr = &x;
}
// x goes out of scope and memory allocated to x is free now.
// So ptr is a dangling pointer now.
Q #7) Describe static function with its usage?
Ans) A function, which has a function definition prefixed with a static keyword is defined as a static function. The static function should call within the same source code.
Q #8) What is the difference between abs() and fabs() functions?
Ans) Both functions are to retrieve absolute value. abs() is for integer values and fabs() is for floating type numbers. Prototype for abs() is under the library file < stdlib.h > and fabs() is under < math.h >.
Q #9) Describe Wild Pointers in C?
Ans) Uninitialized pointers in the C code are known as Wild Pointers. These are a point to some arbitrary memory location and can cause bad program behavior or program crash.
Q #10) What is the difference between ++a and a++?
Ans) ‘++a” is called prefixed increment and the increment will happen first on a variable. ‘a++' is called postfix increment and the increment happens after the value of a variable used for the operations.
Q #11) Describe the difference between = and == symbols in C programming?
Ans) ‘==' is the comparison operator which is used to compare the value or expression on the left-hand side with the value or expression on the right-hand side.
‘=' is the assignment operator which is used to assign the value of the right-hand side to the variable on the left-hand side.
Q #12) What is the explanation for prototype function in C?
Ans) Prototype function is a declaration of a function with the following information to the compiler.
- Name of the function.
- The return type of the function.
- Parameters list of the function.
In this example Name of the function is Sum, the return type is integer data type and it accepts two integer parameters.
Q #13) What is the explanation for the cyclic nature of data types in C?
Ans) Some of the data types in C have special characteristic nature when a developer assigns value beyond the range of the data type. There will be no compiler error and the value change according to a cyclic order. This is called cyclic nature and char, int, long int data types have this property. Further float, double and long double data types do not have this property.
This is called cyclic nature and char, int, long int data types have this property. Further float, double and long double data types do not have this property.
Q #14) Describe the header file and its usage in C programming?
Ans) The file contains the definitions and prototypes of the functions being used in the program are called a header file. It is also known as a library file.
Example– The header file contains commands like printf and scanf is the stdio.h.
Q #15) There is a practice in coding to keep some code blocks in comment symbols than delete it when debugging. How this affects when debugging?
Ans) This concept called commenting out and is the way to isolate some part of the code which scans possible reason for the error. Also, this concept helps to save time because if the code is not the reason for the issue it can simply uncomment.
Q #16) What are the general description for loop statements and available loop types in C?
Ans) A statement that allows executing statements or groups of statements in a repeated way is defined as a loop. Following diagram explains
The following diagram explains a general form of a loop.
There are 4 types of loop statements in C.
- While loop
- For Loop
- Do…While Loop
- Nested Loop
Q #17) What is a nested loop?
Ans) A loop running within another loop is referred to as a nested loop. The first loop is called the Outer loop and inside the loop is called the Inner loop. The inner loop executes the number of times define an outer loop.
Q #18) What is the general form of function in C?
Ans) Function definition in C contains four main sections.
- Return Type -> Data type of the return value of the function.
- Function Name -> The name of the function and it is important to have a meaningful name that describes the activity of the function.
- Parameters -> The input values for the function that needs to use perform the required action.
- Function Body -> Collection of statement that needs to perform the required action.
Q #20) What are the valid places to have keyword “Break”?
Ans) The purpose of the Break keyword is to bring the control out of the code block which is executing. It can appear only in Looping or switch statements.
Q #21) What is the behavioral difference when include header file in double quotes (“”) and angular braces (<>)?
Ans) When the Header file includes within double quotes (“”), compiler search first in the working directory for the particular header file. If not found then in the built-in the include path. But when the Header file includes within angular braces (<>), the compiler only searches in the working directory for the particular header file.
Q #22) What is a sequential access file?
Ans) In general programs store data into files and retrieve existing data from files. With the sequential access file such data saved in a sequential pattern. When retrieving data from such files each data needs to read one by one until the required information found.
Q #23) What is the method to save data in a stack data structure type?
Ans) Data is stored in Stack data structure type using First in Last out (FILO) mechanism. Only top of the stack is accessible at a given instance. Storing mechanism is referred to as a PUSH and retrieve is referred as a POP.
Q #24) What is the significance of C program algorithms?
Ans) The algorithm needs to create first and it contains step by step guidelines on how the solution should create. Also, it contains the steps to consider and the required calculations/operations within the program.
Q #28) What is the incorrect operator form following list(== , <> , >= , <=) and what is the reason for the answer?
Ans) Incorrect operator is ‘<>'.This is the format correct when writing conditional statements, but it is not a correct operation to indicate not equal in C programming and it gives compilation error as follows.
Q #29) Is it possible to use curly brackets ({}) to enclose a single line code in C program?
Ans) Yes, it is working without any error. Some programmers like to use this to organize the code. But the main purpose of curly brackets is to group several lines of codes.
Q #30) Describe the modifier in C?
Ans) Modifier is a prefix to the basic data type which is used to indicate the modification for storage space allocation to a variable.
Example– In 32-bit processor storage space for the int data type is 4.When we use it with modifier the storage space change as follows.
- Long int -> Storage space is 8 bit
- Short int -> Storage space is 2 bit
Q #31) What are the modifiers available in C programming language?
Ans) There are 5 modifiers available in C programming language as follows.
- Short
- Long
- Signed
- Unsigned
- long long
Q #35) Is there any possibility to create a customized header file with C programming language?
Ans) It is possible and easy to create a new header file. Create a file with function prototypes that need to use inside the program. Include the file in the ‘#include' section from its name.
Q #36) Describe dynamic data structure in C programming language?
Ans) Dynamic data structure is more efficient to memory. The memory access occurs as needed by the program.
Q #37) Is that possible to add pointers to each other?
Ans) There is no possibility to add pointers together. Since pointer contains address details there is no way to retrieve the value from this operation.
Q #38) What is indirection?
Ans) If you have defined a pointer to a variable or any memory object, there is no direct reference to the value of the variable. This is called indirect reference. But when we declare a variable it has a direct reference to the value.
Q #39) What are the ways to a null pointer that can use in the C programming language?
Ans) Null pointers are possible to use in three ways.
- As an error value.
- As a sentinel value.
- To terminate indirection in the recursive data structure.
Q #40) What is the explanation for modular programming?
Ans) The process of dividing the main program into executable subsection is called module programming. This concept promotes reusability.
Another Very Important Questions
2) What happens when you compile a program in C? (tricky question)
Whenever you compile a program in C, a multi-stage process takes places. The process is as shown below. Click here to know the complete process & function of compiler, assembles, linker and loader in this process.
4) What happens if a headerfile is included twice? (tricky question)
When the preprocessor sees a #include, it replaces the #include with the contents of the specified header. By using include guard(#), you can prevent a header file from being included multiple times during the compilation process. So basically, if a header file with proper syntax is included twice, the second one gets ignored.
5) Can a program be compiled without the main() function?
Yes, compilation is possible, but the execution is not possible. However, if you use #define, we can execute the program without the need of main().
For Example:
#include <stdio.h>
#define start main
void start() {
printf("Hi");
}
C Programming Interview Questions on Data Types, Variables & keywords
6) What are the basic data types in C?
- Int – Used to represent a number (integer)
- Float – Used to represent a decimal number
- Double – Used to represent a decimal number with highest precision(digits after the decimal point)
- Char – Single character
- Void – Special purpose type without any value
8) What are the various Keywords used in C?
There are 32 various keywords in C and each of them performs a defined function. These keywords are also called as Reserved words.
9) What is the difference between static & global variables?
Global variables are variables which are defined outside the function. The scope of global variables begins at the point where they are defined and lasts till the end of the file/program. Whereas, static global variables are private to the source file where they are defined and do not conflict with other variables in other source files which would have the same name.
11) What is Static and Dynamic memory allocation?
- Static memory allocation happens at compile-time, and memory can’t be increased while executing the program.
- Whereas in case of dynamic memory allocation, this happens at runtime and memory can be increased while executing the program.
- Static memory allocation is used in arrays & dynamic memory allocation is used in Linked Lists.
- Static memory allocation uses more memory space to store a variable.
C Programming Interview Questions on Operators, Input/output
13) What is the difference between while (0) and while (1)?
While(1) is an infinite loop which will run till a break statement occurs. Similarly, while(2), while(3), while(255) etc will all give infinite loops only.
Whereas, While(0) does the exact opposite of this. When while(0) is used, it means the conditions will always be false. Thus, as a result, the program will never get executed.
C Programming Interview Questions on Arrays, Strings, Pointers & Functions
15) What is the difference between the Void and Null Pointer?
Null pointers generally do not point to a valid location. A pointer is initialized as NULL if we are not aware of its value at the time of declaration.
Whereas, Void pointers are general-purpose pointers which do not have any type associated with them and can contain the address of any type of variable. So basically, the type of data that it points to can be anything.
16) What is the difference between Pass by value and Pass by reference?
In pass by value, changes made to the arguments in the called function will not be reflected in the calling function. Whereas in pass by reference, the changes made to the arguments in the called function will be reflected in the calling function.
The below image will help you get a good understanding.
17) What is a pointer on a pointer in C programming language?
A pointer variable that contains the address of another pointer variable is called as a pointer on a pointer. For example, consider the following program.
int main()
{
int v1 = 54;
int *pointer2; // pointer for var
int **pointer1; // double pointer for ptr2
pointer2 = &v1; // storing address of var in ptr2
pointer1 = &pointer2; // Storing address of ptr2 in ptr1
printf("Value of v1 = %d\n", v1);
printf("Value of v1 using single pointer = %d\n", *pointer2 );
printf("Value of v1 using double pointer = %d\n", **pointer1);
return 0;
}
18) Difference between malloc() and calloc() functions?
malloc and calloc are library functions that allocate memory dynamically, which means that memory is allocated during the runtime from the heap segment.
Malloc and Calloc differ in the number of arguments used, their initialization methods and also in the return values.
19) What is the difference between Arrays and Pointers?
A few differences between Arrays and Pointers are:
- An array is a collection of elements of similar data type whereas the pointer is a variable that stores the address of another variable.
- An array size decides the number of variables it can store whereas; a pointer variable can store the address of only one variable in it.
- Arrays can be initialized at the definition, while pointers cannot be initialized at the definition.
20) What is the difference between a structure and a Union?
- All the members of a structure can be accessed simultaneously but union can access only one member at a time
- Altering the value of a member will not affect the other members of the structure but where it affects the members of a union
- Lesser memory is needed for a union variable than a structure variable of the same type
C Interview Programs with Solutions
21) Write a program to print “hello world” without using a semicolon?
#include <stdio.h>
void main()
{
if(printf("hello world"))
{
}}
22) How to swap two numbers without the use of the third variable?
#include<stdio.h>
main()
{
int a=1, b=8;
printf("Before swapping a=%d b=%d",a,b);a=a+b;//a=30
b=a-b;//b=10
a=a-b;//a=20
printf("After swapping a=%d b=%d",a,b);
getch();
}
23) Program to reverse a given number in C
24) Program to print factorial of a number
25) Print Fibonacci series up to n
26) Print all the prime numbers in a given range
27) Check if a given number is an Armstrong number or not.
28) Replace all 0’s with 1 in a given integer.
29) Pyramid pattern using stars
*
* *
* * *
* * * *
* * * * *
* * * * * *
*
* *
* * *
* * * *
* * * * *
* * * * * *
30) Reverse a string using recursion
Q3. What do you mean by the Scope of the variable? What is the scope of the variables in C?
Ans: Scope of the variable can be defined as the part of the code area where the variables declared in the program can be accessed directly. In C, all identifiers are lexically (or statically) scoped.
Q4. What are static variables and functions?
Ans: The variables and functions that are declared using the keyword Static are considered as Static Variable and Static Functions. The variables declared using Static keyword will have their scope restricted to the function in which they are declared.
Q5. Differentiate between calloc() and malloc()
Ans: calloc() and malloc() are memory dynamic memory allocating functions. The only difference between them is that calloc() will load all the assigned memory locations with value 0 but malloc() will not.
Q6. What are the valid places where the programmer can apply Break Control Statement?
Ans: Break Control statement is valid to be used inside a loop and Switch control statements.
Q7. How can we store a negative integer?
Ans: To store a negative integer, we need to follow the following steps. Calculate the two’s complement of the same positive integer.
Eg: 1011 (-5)
Step-1 − One’s complement of 5: 1010
Step-2 − Add 1 to above, giving 1011, which is -
Q8. Differentiate between Actual Parameters and Formal Parameters.
Ans: The Parameters which are sent from main function to the subdivided function are called as Actual Parameters and the parameters which are declared a the Subdivided function end are called as Formal Parameters.
Q9. Can a C program be compiled or executed in the absence of a main()?
Ans: The program will be compiled but will not be executed. To execute any C program, main() is required.
Q10. What do you mean by a Nested Structure?
Ans: When a data member of one structure is referred by the data member of another function, then the structure is called a Nested Structure.
Q11. What is a C Token?
Ans: Keywords, Constants, Special Symbols, Strings, Operators, Identifiers used in C program are referred to as C Tokens.
Q12. What is Preprocessor?
Ans: A Preprocessor Directive is considered as a built-in predefined function or macro that acts as a directive to the compiler and it gets executed before the actual C Program is executed.
Q13. Why is C called the Mother of all Languages?
Ans: C introduced many core concepts and data structures like arrays, lists, functions, strings, etc. Many languages designed after C are designed on the basis of C Language. Hence, it is considered as the mother of all languages.
Q15. What is the purpose of printf() and scanf() in C Program?
Ans: printf() is used to print the values on the screen. To print certain values, and on the other hand, scanf() is used to scan the values. We need an appropriate datatype format specifier for both printing and scanning purposes. For example,
- %d: It is a datatype format specifier used to print and scan an integer value.
- %s: It is a datatype format specifier used to print and scan a string.
- %c: It is a datatype format specifier used to display and scan a character value.
- %f: It is a datatype format specifier used to display and scan a float value.
Q16. What is an array?
Ans. The array is a simple data structure that stores multiple elements of the same datatype in a reserved and sequential manner. There are three types of arrays, namely,
- One Dimensional Array
- Two Dimensional Array
- Multi-Dimensional Array
Q17. What is /0 character?
Ans: The Symbol mentioned is called a Null Character. It is considered as the terminating character used in strings to notify the end of the string to the compiler.
Q18. What is the main difference between the Compiler and the Interpreter?
Ans: Compiler is used in C Language and it translates the complete code into the Machine Code in one shot. On the other hand, Interpreter is used in Java Programming Langauge and other high-end programming languages. It is designed to compile code in line by line fashion.
Q20. How is a Function declared in C Language?
Ans: A function in C language is declared as follows,
1
2
3
4
return_type function_name(formal parameter list)
{
Function_Body;
}
Q21. What is Dynamic Memory allocation? Mention the syntax.
Ans: Dynamic Memory Allocation is the process of allocating memory to the program and its variables in runtime. Dynamic Memory Allocation process involves three functions for allocating memory and one function to free the used memory.
malloc() – Allocates memory
Syntax:
1
ptr = (cast-type*) malloc(
byte
-size);
calloc() – Allocates memory
Syntax:
1
ptr = (cast-type*)calloc(n, element-size);
realloc() – Allocates memory
Syntax:
1
ptr = realloc(ptr, newsize);
free() – Deallocates the used memory
Syntax:
1
free(ptr);
Q23. Where can we not use &(address operator in C)?
Ans: We cannot use & on constants and on a variable which is declared using the register storage class
Q24. Write a simple example of a structure in C Language
Ans: Structure is defined as a user-defined data type that is designed to store multiple data members of the different data types as a single unit. A structure will consume the memory equal to the summation of all the data members.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct employee
{
char
name[
10
];
int
age;
}e1;
int
main()
{
printf(
"Enter the name"
);
scanf(
"%s"
,e1.name);
printf(
"n"
);
printf(
"Enter the age"
);
scanf(
"%d"
,&e1.age);
printf(
"n"
);
printf(
"Name and age of the employee: %s,%d"
,e1.name,e1.age);
return
0
;
}
Q25. Differentiate between call by value and call by reference
Ans:
Factor Call by Value Call by Reference
Safety Actual arguments cannot be changed and remain safe Operations are performed on actual arguments, hence not safe
Memory Location Separate memory locations are created for actual and formal arguments Actual and Formal arguments share the same memory space.
Arguments Copy of actual arguments are sent Actual arguments are passed
//Example of Call by Value method
#include<stdio.h>
void
change(
int
,
int
);
int
main()
{
int
a=
25
,b=
50
;
change(a,b);
printf(
"The value assigned to a is: %d"
,a);
printf(
"n"
);
printf(
"The value assigned to of b is: %d"
,b);
return
0
;
}
void
change(
int
x,
int
y)
{
x=
100
;
y=
200
;
}
//Output
The value assigned to of a is: 25
The value assigned to of b is: 50
//Example of Call by Reference method
#include<stdio.h>
void
change(
int
*,
int
*);
int
main()
{
int
a=
25
,b=
50
;
change(&a,&b);
printf(
"The value assigned to a is: %d"
,a);
printf(
"n"
);
printf(
"The value assigned to b is: %d"
,b);
return
0
;
}
void
change(
int
*x,
int
*y)
{
*x=
100
;
*y=
200
;
}
//Output
The value assigned to a is: 100
The value assigned to b is: 200
Q26. Differentiate between getch() and getche()
Ans: Both the functions are designed to read characters from the keyboard and the only difference is that
getch(): reads characters from the keyboard but it does not use any buffers. Hence, data is not displayed on the screen.
getche(): reads characters from the keyboard and it uses a buffer. Hence, data is displayed on the screen.
//Example
#include<stdio.h>
#include<conio.h>
int
main()
{
char
ch;
printf(
"Please enter a character "
);
ch=getch();
printf(
"nYour entered character is %c"
,ch);
printf(
"nPlease enter another character "
);
ch=getche();
printf(
"nYour new character is %c"
,ch);
return
0
;
}
//Output
Please enter a character
Your entered character is x
Please enter another character z
Your new character is z
Q27. Explain toupper() with an example.
Ans. toupper() is a function designed to convert lowercase words/characters into upper case.
//Example
#include<stdio.h>
#include<ctype.h>
int
main()
{
char
c;
c=a;
printf(
"%c after conversions %c"
, c, toupper(c));
c=B;
printf(
"%c after conversions %c"
, c, toupper(c));
}
//Output:
a after conversions A
B after conversions B
Q28. Write a code to generate random numbers in C Language
Ans: Random numbers in C Language can be generated as follows:
#include<stdio.h>
#include<stdlib.h>
int
main()
{
int
a,b;
for
(a=
1
;a<=
10
;a++)
{
b=rand();
printf(
"%dn"
,b);
}
return
0
;
}
//Output
1987384758
2057844389
3475398489
2247357398
1435983905
Q29. Can I create a customized Head File in C language?
Ans: It is possible to create a new header file. Create a file with function prototypes that need to be used in the program. Include the file in the ‘#include’ section in its name.
Q31. Explain Local Static Variables and what is their use?
Ans: A local static variable is a variable whose life doesn’t end with a function call where it is declared. It extends for the lifetime of the complete program. All calls to the function share the same copy of local static variables.
#include<stdio.h>
void
fun()
{
static
int
x;
printf(
"%d "
, x);
x = x +
1
;
}
int
main()
{
fun();
fun();
return
0
;
}
//Output
0 1
Q32. What is the difference between declaring a header file with < > and ” “?
Ans: If the Header File is declared using < > then the compiler searches for the header file within the Built-in Path. If the Header File is declared using ” ” then the compiler will search for the Header File in the current working directory and if not found then it searches for the file in other locations.
Q33. When should we use the register storage specifier?
Ans: We use Register Storage Specifier if a certain variable is used very frequently. This helps the compiler to locate the variable as the variable will be declared in one of the CPU registers.
Q34. Which statement is efficient and why? x=x+1; or x++;
Ans: x++; is the most efficient statement as it just a single instruction to the compiler while the other is not.
Q35. Can I declare the same variable name to the variables which have different scopes?
Ans: Yes, Same variable name can be declared to the variables with different variable scopes as the following example.
int
var;
void
function()
{
int
variable;
}
int
main()
{
int
variable;
}
Q36. Which variable can be used to access Union data members if the Union variable is declared as a pointer variable?
Ans: Arrow Operator( -> ) can be used to access the data members of a Union if the Union Variable is declared as a pointer variable.
Q37. Mention File operations in C Language.
Ans: Basic File Handling Techniques in C, provide the basic functionalities that user can perform against files in the system.
Function Operation
fopen() To Open a File
fclose() To Close a File
fgets() To Read a File
fprint() To Write into a File
Q38. What are the different storage class specifiers in C?
Ans: The different storage specifiers available in C Language are as follows:
- auto
- register
- static
- extern
Q39. What is typecasting?
Ans: Typecasting is a process of converting one data type into another is known as typecasting. If we want to store the floating type value to an int type, then we will convert the data type into another data type explicitly.
Syntax:
1
(type_name) expression;
Q40. Write a C program to print hello world without using a semicolon ;
Ans:
1
2
3
4
5
#include<stdio.h>
void
main()
{
if
(printf(
"hello world"
)){}
}
//Output:
hello world
Q41. Write a program to swap two numbers without using the third variable.
Ans:
//Output
Before swapping a=10 b=20
After swapping a=20 b=10
Q42. How can you print a string with the symbol % in it?
Ans: There is no escape sequence provided for the symbol % in C. So, to print % we should use ‘%%’ as shown below.
1
printf(“there are
90
%% chances of rain tonight”);
Q43. Write a code to print the following pattern.
1
12
123
1234
12345
Ans: To print the above pattern, the following code can be used.
#include<stdio.h>
int
main()
{
for
(i=
1
;i<=
5
;
1
++)
{
for
(j=
1
;j<=
5
;j++)
{
print(
"%d"
,j);
}
printf(
"n"
);
}
return
0
;
}
Q44. Explain the # pragma directive.
Ans: The following points explain the Pragma Directive.
- This is a preprocessor directive that can be used to turn on or off certain features.
- It is of two types #pragma startup, #pragma exit and pragma warn.
- #pragma startup allows us to specify functions called upon program startup.
- #pragma exit allows us to specify functions called upon program exit.
- #pragma warn tells the computer to suppress any warning or not.
Q48. Which structure is used to link the program and the operating system?
Ans: The answer can be explained through the following points,
- The structure used to link the operating system to a program is file.
- The file is defined in the header file “stdio.h”(standard input/output header file).
- It contains the information about the file being used, its current size and its location in memory.
- It contains a character pointer that points to the character that is being opened.
- Opening a file establishes a link between the program and the operating system about which file is to be accessed.
Q49. What are the limitations of scanf() and how can it be avoided?
Ans: The Limitations of scanf() are as follows:
- scanf() cannot work with the string of characters.
- It is not possible to enter a multiword string into a single variable using scanf().
- To avoid this the gets( ) function is used.
- It gets a string from the keyboard and is terminated when enter key is pressed.
- Here the spaces and tabs are acceptable as part of the input string.
Q50. Differentiate between the macros and the functions.
Ans: The differences between macros and functions can be explained as follows:
- Macro call replaces the templates with the expansion in a literal way.
- The Macro call makes the program run faster but also increases the program size.
- Macro is simple and avoids errors related to the function calls.
- In a function, call control is transferred to the function along with arguments.
- It makes the functions small and compact.
- Passing arguments and getting back the returned value takes time and makes the program run at a slower rate.
Q51. Suppose a global variable and local variable have the same name. Is it is possible to access a global variable from a block where local variables are defined?
Ans: No. It is not possible in C. It is always the most local variable that gets preference.
With this, we come to an end of this “C Programming Interview Questions” article. I hope you have understood the importance of C Programming.
Commonly Asked C Programming Interview Questions
1. What is the difference between declaration and definition of a variable/function
Ans: Declaration of a variable/function simply declares that the variable/function exists somewhere in the program but the memory is not allocated for them. But the declaration of a variable/function serves an important role. And that is the type of the variable/function. Therefore, when a variable is declared, the program knows the data type of that variable. In case of function declaration, the program knows what are the arguments to that functions, their data types, the order of arguments and the return type of the function. So that’s all about declaration.
Coming to the definition, when we define a variable/function, apart from the role of declaration, it also allocates memory for that variable/function. Therefore, we can think of definition as a super set of declaration. (or declaration as a subset of definition). From this explanation, it should be obvious that a variable/function can be declared any number of times but it can be defined only once. (Remember the basic principle that you can’t have two locations of the same variable/function).
2. What are different storage class specifiers in C?
Ans: auto, register, static, extern
3. What is scope of a variable? How are variables scoped in C?
Ans: Scope of a variable is the part of the program where the variable may directly be accessible. In C, all identifiers are lexically (or statically) scoped.
4. How will you print “Hello World” without semicolon?
Ans:
#include <stdio.h>
int
main(
void
)
{
if
(
printf
(
"Hello World"
)) {
}
}
5. When should we use pointers in a C program?
1. To get address of a variable
2. For achieving pass by reference in C: Pointers allow different functions to share and modify their local variables.
3. To pass large structures so that complete copy of the structure can be avoided.
4. To implement “linked” data structures like linked lists and binary trees.
6. What is NULL pointer?
Ans: NULL is used to indicate that the pointer doesn’t point to a valid location. Ideally, we should initialize pointers as NULL if we don’t know their value at the time of declaration. Also, we should make a pointer NULL when memory pointed by it is deallocated in the middle of a program.
8. What is memory leak? Why it should be avoided
Ans: Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.
/* Function with memory leak */
#include <stdlib.h>
void
f()
{
int
* ptr = (
int
*)
malloc
(
sizeof
(
int
));
/* Do some work */
return
;
/* Return without freeing ptr*/
}
9. What are local static variables? What is their use?
Ans:A local static variable is a variable whose lifetime doesn’t end with a function call where it is declared. It extends for the lifetime of complete program. All calls to the function share the same copy of local static variables. Static variables can be used to count the number of times a function is called. Also, static variables get the default value as 0. For example, the following program prints “0 1”
#include <stdio.h>
void
fun()
{
// static variables get the default value as 0.
static
int
x;
printf
(
"%d "
, x);
x = x + 1;
}
int
main()
{
fun();
fun();
return
0;
}
// Output: 0 1
10. What are static functions? What is their use?
Ans:In C, functions are global by default. The “static” keyword before a function name makes it static. Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files.
After reading above 10 questions I will suggest you to watch storage class specifier and type of pointers from sourabh shukla video on youtube.com for perfect clarification.After this read below
12. What is difference between i++ and ++i?
1) The expression ‘i++’ returns the old value and then increments i. The expression ++i increments the value and returns new value.
2) Precedence of postfix ++ is higher than that of prefix ++.
3) Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left.
4) In C++, ++i can be used as l-value, but i++ cannot be. In C, they both cannot be used as l-value.
13. What is l-value?
l-value or location value refers to an expression that can be used on left side of assignment operator. For example in expression “a = 3”, a is l-value and 3 is r-value.
l-values are of two types:
“nonmodifiable l-value” represent a l-value that can not be modified. const variables are “nonmodifiable l-value”.
“modifiable l-value” represent a l-value that can be modified.
14. What is the difference between array and pointer?
15. How to write your own sizeof operator?
#define my_sizeof(type) (char *)(&type+1)-(char*)(&type)
16. How will you print numbers from 1 to 100 without using loop?
We can use recursion for this purpose.
/* Prints numbers from 1 to n */
void
printNos(unsigned
int
n)
{
if
(n > 0)
{
printNos(n-1);
printf
(
"%d "
, n);
}
}
17. What is volatile keyword?
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler.
Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.
18. Can a variable be both const and volatile?
yes, the const means that the variable cannot be assigned a new value. The value can be changed by other code or pointer. For example the following program works fine.
int main(void)
{
const volatile int local = 10;
int *ptr = (int*) &local;
printf("Initial value of local : %d \n", local);
*ptr = 100;
printf("Modified value of local: %d \n", local);
return 0;
}
Question 19. Why N++ Executes Faster Than N+1?
Answer :
The expression n++ requires a single machine instruction such as INR to carry out the increment operation whereas n+1 requires more instructions to carry out this operation.
Here below are some more 100 questions (if you have time read them, otherwise they are covered above)
1) How do you construct an increment statement or decrement statement in C?
There are actually two ways you can do this. One is to use the increment operator ++ and decrement operator –. For example, the statement “x++” means to increment the value of x by 1. Likewise, the statement “x –” means to decrement the value of x by 1. Another way of writing increment statements is to use the conventional + plus sign or – minus sign. In the case of “x++”, another way to write it is “x = x +1”.
2) What is the difference between Call by Value and Call by Reference?
When using Call by Value, you are sending the value of a variable as parameter to a function, whereas Call by Reference sends the address of the variable. Also, under Call by Value, the value in the parameter is not affected by whatever operation that takes place, while in the case of Call by Reference, values can be affected by the process within the function.
3) Some coders debug their programs by placing comment symbols on some codes instead of deleting it. How does this aid in debugging?
Placing comment symbols /* */ around a code, also referred to as “commenting out”, is a way of isolating some codes that you think maybe causing errors in the program, without deleting the code. The idea is that if the code is in fact correct, you simply remove the comment symbols and continue on. It also saves you time and effort on having to retype the codes if you have deleted it in the first place.
4) What is the equivalent code of the following statement in WHILE LOOP format?
1
2
3
for (a=1; a<=100; a++)
printf ("%d\n", a * a);
Answer:
1
2
3
4
5
6
7
8
9
a=1;
while (a<=100) {
printf ("%d\n", a * a);
a++;
}
5) What is a stack?
A stack is one form of a data structure. Data is stored in stacks using the FILO (First In Last Out) approach. At any particular instance, only the top of the stack is accessible, which means that in order to retrieve data that is stored inside the stack, those on the upper part should be extracted first. Storing data in a stack is also referred to as a PUSH, while data retrieval is referred to as a POP.
6) What is a sequential access file?
When writing programs that will store and retrieve data in a file, it is possible to designate that file into different forms. A sequential access file is such that data are saved in sequential order: one data is placed into the file after another. To access a particular data within the sequential access file, data has to be read one data at a time, until the right one is reached.
7) What is variable initialization and why is it important?
This refers to the process wherein a variable is assigned an initial value before it is used in the program. Without initialization, a variable would have an unknown value, which can lead to unpredictable outputs when used in computations or other operations.
8 What is spaghetti programming?
Spaghetti programming refers to codes that tend to get tangled and overlapped throughout the program. This unstructured approach to coding is usually attributed to lack of experience on the part of the programmer. Spaghetti programing makes a program complex and analyzing the codes difficult, and so must be avoided as much as possible.
9) Differentiate Source Codes from Object Codes
Source codes are codes that were written by the programmer. It is made up of the commands and other English-like keywords that are supposed to instruct the computer what to do. However, computers would not be able to understand source codes. Therefore, source codes are compiled using a compiler. The resulting outputs are object codes, which are in a format that can be understood by the computer processor. In C programming, source codes are saved with the file extension .C, while object codes are saved with the file extension .OBJ
10) In C programming, how do you insert quote characters (‘ and “) into the output screen?
This is a common problem for beginners because quotes are normally part of a printf statement. To insert the quote character as part of the output, use the format specifiers \’ (for single quote), and \” (for double quote).
11) What is the use of a ‘\0’ character?
It is referred to as a terminating null character, and is used primarily to show the end of a string value.
13) What is the modulus operator?
The modulus operator outputs the remainder of a division. It makes use of the percentage (%) symbol. For example: 10 % 3 = 1, meaning when you divide 10 by 3, the remainder is 1.
15) Which of the following operators is incorrect and why? ( >=, <=, <>, ==)
<> is incorrect. While this operator is correctly interpreted as “not equal to” in writing conditional statements, it is not the proper operator to be used in C programming. Instead, the operator != must be used to indicate “not equal to” condition.
16) Compare and contrast compilers from interpreters.
Compilers and interpreters often deal with how program codes are executed. Interpreters execute program codes one line at a time, while compilers take the program as a whole and convert it into object code, before executing it. The key difference here is that in the case of interpreters, a program may encounter syntax errors in the middle of execution, and will stop from there. On the other hand, compilers check the syntax of the entire program and will only proceed to execution when no syntax errors are found.
17) How do you declare a variable that will hold string values?
The char keyword can only hold 1 character value at a time. By creating an array of characters, you can store string values in it. Example: “char MyName[50]; ” declares a string variable named MyName that can hold a maximum of 50 characters.
18) Can the curly brackets { } be used to enclose a single line of code?
While curly brackets are mainly used to group several lines of codes, it will still work without error if you used it for a single line. Some programmers prefer this method as a way of organizing codes to make it look clearer, especially in conditional statements.
21) What are variables and it what way is it different from constants?
Variables and constants may at first look similar in a sense that both are identifiers made up of one character or more characters (letters, numbers and a few allowable symbols). Both will also hold a particular value. Values held by a variable can be altered throughout the program, and can be used in most operations and computations. Constants are given values at one time only, placed at the beginning of a program. This value is not altered in the program. For example, you can assigned a constant named PI and give it a value 3.1415 . You can then use it as PI in the program, instead of having to write 3.1415 each time you need it.
22) How do you access the values within an array?
Arrays contain a number of elements, depending on the size you gave it during variable declaration. Each element is assigned a number from 0 to number of elements-1. To assign or retrieve the value of a particular element, refer to the element number. For example: if you have a declaration that says “intscores[5];”, then you have 5 accessible elements, namely: scores[0], scores[1], scores[2], scores[3] and scores[4].
23) Can I use “int” data type to store the value 32768? Why?
No. “int” data type is capable of storing values from -32768 to 32767. To store 32768, you can use “long int” instead. You can also use “unsigned int”, assuming you don’t intend to store negative values.
24) Can two or more operators such as \n and \t be combined in a single line of program code?
Yes, it’s perfectly valid to combine operators, especially if the need arises. For example: you can have a code like ” printf (“Hello\n\n\’World\'”) ” to output the text “Hello” on the first line and “World” enclosed in single quotes to appear on the next two lines.
25) Why is it that not all header files are declared in every C program?
The choice of declaring a header file at the top of each C program would depend on what commands/functions you will be using in that program. Since each header file contains different function definitions and prototype, you would be using only those header files that would contain the functions you will need. Declaring all header files in every program would only increase the overall file size and load of the program, and is not considered a good programming style.
26) When is the “void” keyword used in a function?
When declaring functions, you will decide whether that function would be returning a value or not. If that function will not return a value, such as when the purpose of a function is to display some outputs on the screen, then “void” is to be placed at the leftmost part of the function header. When a return value is expected after the function execution, the data type of the return value is placed instead of “void”.
27) What are compound statements?
Compound statements are made up of two or more program statements that are executed together. This usually occurs while handling conditions wherein a series of statements are executed when a TRUE or FALSE is evaluated. Compound statements can also be executed within a loop. Curly brackets { } are placed before and after compound statements.
28) What is the significance of an algorithm to C programming?
Before a program can be written, an algorithm has to be created first. An algorithm provides a step by step procedure on how a solution can be derived. It also acts as a blueprint on how a program will start and end, including what process and computations are involved.
29) What is the advantage of an array over individual variables?
When storing multiple related data, it is a good idea to use arrays. This is because arrays are named using only 1 word followed by an element number. For example: to store the 10 test results of 1 student, one can use 10 different variable names (grade1, grade2, grade3… grade10). With arrays, only 1 name is used, the rest are accessible through the index name (grade[0], grade[1], grade[2]… grade[9]).
30) Write a loop statement that will show the following output:
1
12
123
1234
12345
Answer:
1
2
3
4
5
6
7
8
9
for (a=1; a<=5; i++) {
for (b=1; b<=a; b++)
printf("%d",b);
printf("\n");
}
31) What is wrong in this statement? scanf(“%d”,whatnumber);
An ampersand & symbol must be placed before the variable name whatnumber. Placing & means whatever integer value is entered by the user is stored at the “address” of the variable name. This is a common mistake for programmers, often leading to logical errors.
33) What could possibly be the problem if a valid function name such as tolower() is being reported by the C compiler as undefined?
The most probable reason behind this error is that the header file for that function was not indicated at the top of the program. Header files contain the definition and prototype for functions and commands used in a C program. In the case of “tolower()”, the code “#include <ctype.h>” must be present at the beginning of the program.
34) What are comments and how do you insert it in a C program?
Comments are a great way to put some remarks or description in a program. It can serves as a reminder on what the program is all about, or a description on why a certain code or function was placed there in the first place. Comments begin with /* and ended by */ characters. Comments can be a single line, or can even span several lines. It can be placed anywhere in the program.
35) What is debugging?
Debugging is the process of identifying errors within a program. During program compilation, errors that are found will stop the program from executing completely. At this state, the programmer would look into the possible portions where the error occurred. Debugging ensures the removal of errors, and plays an important role in ensuring that the expected program output is met.
36) What does the && operator do in a program code?
The && is also referred to as AND operator. When using this operator, all conditions specified must be TRUE before the next action can be performed. If you have 10 conditions and all but 1 fails to evaluate as TRUE, the entire condition statement is already evaluated as FALSE.
37) In C programming, what command or code can be used to determine if a number of odd or even?
There is no single command or function in C that can check if a number is odd or even. However, this can be accomplished by dividing that number by 2, then checking the remainder. If the remainder is 0, then that number is even, otherwise, it is odd. You can write it in code as:
1
2
3
4
5
6
7
if (num % 2 == 0)
printf("EVEN");
else
printf("ODD");
38) What does the format %10.2 mean when included in a printf statement?
This format is used for two things: to set the number of spaces allotted for the output number and to set the number of decimal places. The number before the decimal point is for the allotted space, in this case it would allot 10 spaces for the output number. If the number of space occupied by the output number is less than 10, addition space characters will be inserted before the actual output number. The number after the decimal point sets the number of decimal places, in this case, it’s 2 decimal spaces.
39) What are logical errors and how does it differ from syntax errors?
Program that contains logical errors tend to pass the compilation process, but the resulting output may not be the expected one. This happens when a wrong formula was inserted into the code, or a wrong sequence of commands was performed. Syntax errors, on the other hand, deal with incorrect commands that are misspelled or not recognized by the compiler.
40) What are the different types of control structures in programming?
There are 3 main control structures in programming: Sequence, Selection and Repetition. Sequential control follows a top to bottom flow in executing a program, such that step 1 is first perform, followed by step 2, all the way until the last step is performed. Selection deals with conditional statements, which mean codes are executed depending on the evaluation of conditions as being TRUE or FALSE. This also means that not all codes may be executed, and there are alternative flows within. Repetitions are also known as loop structures, and will repeat one or two program statements set by a counter.
41) What is || operator and how does it function in a program?
The || is also known as the OR operator in C programming. When using || to evaluate logical conditions, any condition that evaluates to TRUE will render the entire condition statement as TRUE.
42) Can the “if” function be used in comparing strings?
No. “if” command can only be used to compare numerical values and single character values. For comparing string values, there is another function called strcmp that deals specifically with strings.
43) What are preprocessor directives?
Preprocessor directives are placed at the beginning of every C program. This is where library files are specified, which would depend on what functions are to be used in the program. Another use of preprocessor directives is the declaration of constants.Preprocessor directives begin with the # symbol.
44) What will be the outcome of the following conditional statement if the value of variable s is 10?
s >=10 && s < 25 && s!=12
The outcome will be TRUE. Since the value of s is 10, s >= 10 evaluates to TRUE because s is not greater than 10 but is still equal to 10. s< 25 is also TRUE since 10 is less then 25. Just the same, s!=12, which means s is not equal to 12, evaluates to TRUE. The && is the AND operator, and follows the rule that if all individual conditions are TRUE, the entire statement is TRUE.
45) Describe the order of precedence with regards to operators in C.
Order of precedence determines which operation must first take place in an operation statement or conditional statement. On the top most level of precedence are the unary operators !, +, – and &. It is followed by the regular mathematical operators (*, / and modulus % first, followed by + and -). Next in line are the relational operators <, <=, >= and >. This is then followed by the two equality operators == and !=. The logical operators && and || are next evaluated. On the last level is the assignment operator =.
46) What is wrong with this statement? myName = “Robin”;
You cannot use the = sign to assign values to a string variable. Instead, use the strcpy function. The correct statement would be: strcpy(myName, “Robin”);
47) How do you determine the length of a string value that was stored in a variable?
To get the length of a string value, use the function strlen(). For example, if you have a variable named FullName, you can get the length of the stored string value by using this statement: I = strlen(FullName); the variable I will now have the character length of the string value.
48) Is it possible to initialize a variable at the time it was declared?
Yes, you don’t have to write a separate assignment statement after the variable declaration, unless you plan to change it later on. For example: char planet[15] = “Earth”; does two things: it declares a string variable named planet, then initializes it with the value “Earth”.
50) What are the different file extensions involved when programming in C?
Source codes in C are saved with .C file extension. Header files or library files have the .H file extension. Every time a program source code is successfully compiled, it creates an .OBJ object file, and an executable .EXE file.
51) What are reserved words?
Reserved words are words that are part of the standard C language library. This means that reserved words have special meaning and therefore cannot be used for purposes other than what it is originally intended for. Examples of reserved words are int, void, and return.
52) What are linked list?
A linked list is composed of nodes that are connected with another. In C programming, linked lists are created using pointers. Using linked lists is one efficient way of utilizing memory for storage.
53) What is FIFO?
In C programming, there is a data structure known as queue. In this structure, data is stored and accessed using FIFO format, or First-In-First-Out. A queue represents a line wherein the first data that was stored will be the first one that is accessible as well.
54) What are binary trees?
Binary trees are actually an extension of the concept of linked lists. A binary tree has two pointers, a left one and a right one. Each side can further branch to form additional nodes, which each node having two pointers as well.
55) Not all reserved words are written in lowercase. TRUE or FALSE?
FALSE. All reserved words must be written in lowercase; otherwise the C compiler would interpret this as unidentified and invalid.
57) What would happen to X in this expression: X += 15; (assuming the value of X is 5)
X +=15 is a short method of writing X = X + 15, so if the initial value of X is 5, then 5 + 15 = 20.
58) In C language, the variables NAME, name, and Name are all the same. TRUE or FALSE?
FALSE. C language is a case sensitive language. Therefore, NAME, name and Name are three uniquely different variables.
59) What is an endless loop?
An endless loop can mean two things. One is that it was designed to loop continuously until the condition within the loop is met, after which a break function would cause the program to step out of the loop. Another idea of an endless loop is when an incorrect loop condition was written, causing the loop to run erroneously forever. Endless loops are oftentimes referred to as infinite loops.
60) What is a program flowchart and how does it help in writing a program?
A flowchart provides a visual representation of the step by step procedure towards solving a given problem. Flowcharts are made of symbols, with each symbol in the form of different shapes. Each shape may represent a particular entity within the entire program structure, such as a process, a condition, or even an input/output phase.
61) What is wrong with this program statement? void = 10;
The word void is a reserved word in C language. You cannot use reserved words as a user-defined variable.
62) Is this program statement valid? INT = 10.50;
Assuming that INT is a variable of type float, this statement is valid. One may think that INT is a reserved word and must not be used for other purposes. However, recall that reserved words are express in lowercase, so the C compiler will not interpret this as a reserved word.
63) What are actual arguments?
When you create and use functions that need to perform an action on some given values, you need to pass these given values to that function. The values that are being passed into the called function are referred to as actual arguments.
64) What is a newline escape sequence?
A newline escape sequence is represented by the \n character. This is used to insert a new line when displaying data in the output screen. More spaces can be added by inserting more \n characters. For example, \n\n would insert two spaces. A newline escape sequence can be placed before the actual output expression or after.
65) What is output redirection?
It is the process of transferring data to an alternative output source other than the display screen. Output redirection allows a program to have its output saved to a file. For example, if you have a program named COMPUTE, typing this on the command line as COMPUTE >DATA can accept input from the user, perform certain computations, then have the output redirected to a file named DATA, instead of showing it on the screen.
66) What are run-time errors?
These are errors that occur while the program is being executed. One common instance wherein run-time errors can happen is when you are trying to divide a number by zero. When run-time errors occur, program execution will pause, showing which program line caused the error.
68) What are formal parameters?
In using functions in a C program, formal parameters contain the values that were passed by the calling function. The values are substituted in these formal parameters and used in whatever operations as indicated within the main body of the called function.
69) What are control structures?
Control structures take charge at which instructions are to be performed in a program. This means that program flow may not necessarily move from one statement to the next one, but rather some alternative portions may need to be pass into or bypassed from, depending on the outcome of the conditional statements.
71) When is a “switch” statement preferable over an “if” statement?
The switch statement is best used when dealing with selections based on a single variable or expression. However, switch statements can only evaluate integer and character data types.
72) What are global variables and how do you declare them?
Global variables are variables that can be accessed and manipulated anywhere in the program. To make a variable global, place the variable declaration on the upper portion of the program, just after the preprocessor directives section.
73) What are enumerated types?
Enumerated types allow the programmer to use more meaningful words as values to a variable. Each item in the enumerated type variable is actually associated with a numeric code. For example, one can create an enumerated type variable named DAYS whose values are Monday, Tuesday… Sunday.
75) Is it possible to have a function as a parameter in another function?
Yes, that is allowed in C programming. You just need to include the entire function prototype into the parameter field of the other function where it is to be used.
76) What are multidimensional arrays?
Multidimensional arrays are capable of storing data in a two or more dimensional structure. For example, you can use a 2 dimensional array to store the current position of pieces in a chess game, or position of players in a tic-tac-toe program.
77) Which function in C can be used to append a string to another string?
The strcat function. It takes two parameters, the source string and the string value to be appended to the source string.
78) What is the difference between functions getch() and getche()?
Both functions will accept a character input value from the user. When using getch(), the key that was pressed will not appear on the screen, and is automatically captured and assigned to a variable. When using getche(), the key that was pressed by the user will appear on the screen, while at the same time being assigned to a variable.
79) Dothese two program statements perform the same output? 1) scanf(“%c”, &letter); 2) letter=getchar()
Yes, they both do the exact same thing, which is to accept the next key pressed by the user and assign it to variable named letter.
80) What are structure types in C?
Structure types are primarily used to store records. A record is made up of related fields. This makes it easier to organize a group of related data.
81) What does the characters “r” and “w” mean when writing programs that will make use of files?
“r” means “read” and will open a file as input wherein data is to be retrieved. “w” means “write”, and will open a file for output. Previous data that was stored on that file will be erased.
82) What is the difference between text files and binary files?
Text files contain data that can easily be understood by humans. It includes letters, numbers and other characters. On the other hand, binary files contain 1s and 0s that only computers can interpret.
83) is it possible to create your own header files?
Yes, it is possible to create a customized header file. Just include in it the function prototypes that you want to use in your program, and use the #include directive followed by the name of your header file.
84) What is dynamic data structure?
Dynamic data structure provides a means for storing data more efficiently into memory. Using dynamic memory allocation, your program will access memory spaces as needed. This is in contrast to static data structure, wherein the programmer has to indicate a fix number of memory space to be used in the program.
85) What are the different data types in C?
The basic data types are int, char, and float. Int is used to declare variables that will be storing integer values. Float is used to store real numbers. Char can store individual character values.
86) What is the general form of a C program?
A C program begins with the preprocessor directives, in which the programmer would specify which header file and what constants (if any) to be used. This is followed by the main function heading. Within the main function lies the variable declaration and program statement.
87) What is the advantage of a random access file?
If the amount of data stored in a file is fairly large, the use of random access will allow you to search through it quicker. If it had been a sequential access file, you would have to go through one record at a time until you reach the target data. A random access file lets you jump directly to the target address where data is located.
88) In a switch statement, what will happen if a break statement is omitted?
If a break statement was not placed at the end of a particular case portion? It will move on to the next case portion, possibly causing incorrect output.
89) Describe how arrays can be passed to a user defined function
One thing to note is that you cannot pass the entire array to a function. Instead, you pass to it a pointer that will point to the array first element in memory. To do this, you indicate the name of the array without the brackets.
90) What are pointers?
Pointers point to specific areas in the memory. Pointers contain the address of a variable, which in turn may contain a value or even an address to another memory.
91) Can you pass an entire structure to functions?
Yes, it is possible to pass an entire structure to a function in a call by method style. However, some programmers prefer declaring the structure globally, then pass a variable of that structure type to a function. This method helps maintain consistency and uniformity in terms of argument type.
92) What is gets() function?
The gets() function allows a full line data entry from the user. When the user presses the enter key to end the input, the entire line of characters is stored to a string variable. Note that the enter key is not included in the variable, but instead a null terminator \0 is placed after the last character.
93) The % symbol has a special use in a printf statement. How would you place this character as part of the output on the screen?
You can do this by using %% in the printf statement. For example, you can write printf(“10%%”) to have the output appear as 10% on the screen.
94) How do you search data in a data file using random access method?
Use the fseek() function to perform random access input/ouput on a file. After the file was opened by the fopen() function, the fseek would require three parameters to work: a file pointer to the file, the number of bytes to search, and the point of origin in the file.
95) Are comments included during the compilation stage and placed in the EXE file as well?
No, comments that were encountered by the compiler are disregarded. Comments are mostly for the guidance of the programmer only and do not have any other significant use in the program functionality.
96) Is there a built-in function in C that can be used for sorting data?
Yes, use the qsort() function. It is also possible to create user defined functions for sorting, such as those based on the balloon sort and bubble sort algorithm.
97) What are the advantages and disadvantages of a heap?
Storing data on the heap is slower than it would take when using the stack. However, the main advantage of using the heap is its flexibility. That’s because memory in this structure can be allocated and remove in any particular order. Slowness in the heap can be compensated if an algorithm was well designed and implemented.
98) How do you convert strings to numbers in C?
You can write you own functions to do string to number conversions, or instead use C’s built in functions. You can use atof to convert to a floating point value, atoi to convert to an integer value, and atol to convert to a long integer value.
100) What is the use of a semicolon (;) at the end of every program statement?
It has to do with the parsing process and compilation of the code. A semicolon acts as a delimiter, so that the compiler knows where each statement ends, and can proceed to divide the statement into smaller elements for syntax checking.
No comments:
Post a Comment
If you liked my post or have any kind of trouble , Comment here !!!!