Google News
logo
C-Language Interview Questions
“C” is a structured oriented programming language developed at “AT & T Bell Laboratories of USA” in 1972.  It was developed by Dennis Ritche in late 1970’s. It began to replace the more familiar languages of that time like PL/1, ALGOL etc.
The main features of C language are given below :

Simple
Portable
Mid Level
Structured
Fast Speed
Memory Management
Extensible
printf() function : The printf() function is used for output. It prints the given statement to the console.

Syntax : printf("format string", list of variables);

scanf() function : This function is used to read values using keyboard. It is used for runtime assignment of variables.

Syntax : scanf("format string", list_of_addresses_of_Variables );
Local variable : A variable which is declared inside function or block is known as local variable.

Global variable :  A variable which is declared outside function or block is known as global variable.

int value=50;//global variable  
void function1(){  
int x=20;//local variable  
}  
Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block.

When a local variable is defined, it is not initialized by the system, you must initialize it yourself.

When execution of the block starts the variable is available, and when the block ends the variable 'dies'. It must be declared at the start of the block.

Example :

  void function1()
   {  
      int x=10; //local variable  
   } 
Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it.

Global variables are initialized automatically by the system when you define them.

If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global 

variables and local variables with the same name.

Example :
  int value=20; //global variable  
  void function1()
   {  
     int x=10; //local variable  
   }
C data types are defined as the data storage format that a variable can store a data to perform a specific operation.
Data types are used to define a variable before to use in a program. Size of variable, constant and array are determined by data types.
There are four data types in C language. They are :

Basic data types : int, char, float, double
Enumeration data type : enum
Derived data type : pointer, array, structure, union
Void data type : void
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. There are only 32 reserved words (keywords) in C language. No header file is needed to include the keywords are following :

Keywords : auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static,  struct, switch, typedef, union, unsigned, void, volatile, while.
The symbols which are used to perform logical and mathematical operations in a C program are called C operators.
These C operators join individual constants and variables to form expressions. Operators, functions, constants and variables are combined together to form expressions.

The C language operators are following :

Arithmetic Operators
Assignment Operators
Increment and Decrement
Relational Operators
Logical Operators
Conditional Operators
Bitwise Operators
Special operators
C Arithmetic operators are used to perform mathematical calculations like, Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulo Division (%).

Modulo division produces the remainder of an integer division. During modulo division, the sign of the result is always the sign of the first operand (the dividend).

Example :
- 14 % 3 = -2 
-14 % - 3 = 2
In C program values for the variables are assigned using assignment operators. The most common assignment operator is ‘=’ this operator assign (copy) the right side value to the left side variable.

Example :
var =5;  //5 is assigned to var
a=c;   //value of c is assigned to a
5=c;   // Error! 5 is a constant.
In C, “++” and “--“are called increment and decrement operators respectively. Both of these operators are unary operators, i.e., used on single operand. ++ adds 1 to operand and -- subtracts 1 from operand respectively.

Syntax :
increment operator: ++var_name; (or) var_name++;
Decrement operator: --var_name; (or) var_name--;
Relational Operators are used to find the relation between two variables, and also used to compare arithmetic, logical and character expressions. The value of a relational expression is either one or zero, if the result is one, then the specified relation is true or if the result is zero then the specified relation is false.

Example :
10 < 20 is true 
20 < 10 is false
Logical Operators are used when we want to test more than one condition and make decisions. Here the operands can be constants, variables and expressions.
There are 3 logical operators in c language they are   &&, ||, !
Conditional operator is used to check a condition and Select a Value depending on the Value of the condition. 

Syntax :
Variable = (condition)? Value 1: Value 2:
Bitwise operators are used to perform operations at binary level. Decimal values are converted into binary values these operators are used for testing the bits, or  shifting them right or left. These operators are not applicable to float or double. Following are the Bitwise operators with their meanings.

Operators : 
& : Bitwise AND
| : Bitwise OR
^ : Bitwise Exclusive – OR
<< : Left Shift
>> : Right Shift
~ : Complement
Below are the some important special operators in c language

Comma, : Comma operators are used to link related expressions together.
& : This is used to get the address of the variable
* : This is used as pointer to a variable
sizeof() : This gives the size of the variable
It’s a pointer variable which can hold the address of another pointer variable. It de-refers twice to point to the data held by the designated pointer variable.

Ex : int x = 5, *p=&x, **q=&p;
Therefore ‘x’ can be accessed by **q.
The = symbol is often used in mathematical operations. It is used to assign a value to a given variable. On the other hand, the == symbol, also known as “equal to” or “equivalent to”, is a relational operator that is used to compare two values.
<> 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.
There are 3 types of decision making control statements in C language. They are :

if statements
if else statements
nested if statements
Loop control statements in C are used to perform looping operations until the given condition is true. Control comes out of the loop statements once condition becomes false.

There are 3 types of loop control statements in C language. They are : 

for
while
do-while
While loop is executed only when given condition is true.
Whereas, do-while loop is executed for first time irrespective of the condition. After executing while loop for first time, then condition is checked.
NULL is a macro which is defined in C header files. The value of NULL macro is 0. It is defined in C header files as below.

#define NULL (void *) 0;

NULL is used for pointers only as it is defined as (void *) 0. It should not be used other than pointers. If NULL is assigned to a pointer, then pointer is pointing to  nothing.
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.
C Structure is a collection of different data types which are grouped together and each element in a C structure is called member.

In real life we need to have different data types for ex: To maintain employee information. We should have information such as name, age, qualification, salary etc. here to maintain the information of employee dissimilar data types required. Name & qualification are char data type, age is integer, and salary is float. You can create this information separately but, better approach will be collection of this information under single name because all these information are related to person.
Unions are conceptually similar to structures. The syntax of union is also similar to that of structure. The only difference is in terms of storage. In structure each  member has its own storage location, whereas all members of union use a single shared memory location which is equal to the size of its largest data member.

Example :
      union item 
      {
      int m;
      float x;
      char c;
      }It1;
Enumeration data type used to symbolize a list of constants with valid meaningful names, so that, it makes the program easy to read and modify. Enumeration has advantage of generating the values automatically for given list of names. Keyword enum is used to define enumerated data type.

Syntax : 
  enum type_name
  { 
   value1, value2... valueN 
   };
For every c program it is required to have a proper error handling mechanism that can deal with errors which occur at runtime. Error handling is the process of  responding to the occurrence of any error that occurs during the computation, of exceptions.

errno, perror() and strerror() : 

In C Programming Language we have perror() and strerror() functions which can be used to display the text message associated with errno.

perror() :  It displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value.
strerror() : It returns a pointer to the textual representation of the current errno value.
stderr : It is file stream to output the errors.
A file is a place on disk where group of related data are stored. C supports a number of functions that have the ability to perform basic file operations, which  include : 

Creating a new file
Opening a file 
Reading data from a file 
Writing data to a file 
Closing the file
Both allocates memory from heap area/dynamic memory. By default calloc fills the allocated memory with 0’s.
Break can appear only with in the looping control and switch statement. The purpose of the break is to bring the control out from the said blocks.
Used to resolve the scope of global symbol.
 
Example :  
main() {
   extern int i;
   Printf(“%d”,i);
}

int i = 20;
A pointer initially holding valid address, but later the held address is released or freed. Then such a pointer is called as dangling pointer.
A structure containing the same structure pointer variable as its element is called as self-referential structure.
When a function calls itself, and this process is known as recursion. The function that calls itself is known as a recursive function.
 
Recursive function comes in two phases :
 
* Winding phase
* Unwinding phase

Winding phase : When the recursive function calls itself, and this phase ends when the condition is reached.
 
Unwinding phase : Unwinding phase starts when the condition is reached, and the control returns to the original call.
 
Example of recursion : 
 
#include <stdio.h>  
int calculate_fact(int);  
int main()  
{  
 int n=5,f;  
 f=calculate_fact(n); // calling a function  
 printf("factorial of a number is %d",f);  
  return 0;  
}  
int calculate_fact(int a)  
{  
  if(a==1)  
  {  
      return 1;  
  }  
  else  
  return a*calculate_fact(a-1); //calling a function recursively.  
   }  
 
Output :
 
factorial of a number is 120
Accessing array elements : Pointers are used in traversing through an array of integers and strings. The string is an array of characters which is terminated by a null character '\0'.

Dynamic memory allocation : Pointers are used in allocation and deallocation of memory during the execution of a program.

Call by Reference : The pointers are used to pass a reference of a variable to other function.

Data Structures like a tree, graph, linked list, etc,. : The pointers are used to construct different data structures like tree, graph, linked list, etc.
* In case of static memory allocation, memory is allocated at compile time, and memory can't be increased while executing the program. It is used in the array.

* The lifetime of a variable in static memory is the lifetime of a program.

* The static memory is allocated using static keyword.

* The static memory is implemented using stacks or heap.

* The pointer is required to access the variable present in the static memory.

* The static memory is faster than dynamic memory.

* In static memory, more memory space is required to store the variable.

For example :  
int a[10];  ​
The above example creates an array of integer type, and the size of an array is fixed, i.e., 10.
In C, every local variable of a function is known as an automatic (auto) variable. Variables which are declared inside the function block are known as a local variable. The local variables are also known as an auto variable. It is optional to use an auto keyword before the data type of a variable. If no value is stored in the local variable, then it consists of a garbage value.
Yes, we can compile, but it can't be executed.
 
But, if we use #define, we can compile and run a C program without using the main() function. For example:
 
#include<stdio.h>    
#define start main    
void start() {    
   printf("Hello");    
}
The argument passed to the main() function while executing the program is known as command line argument.

For example :
 
main(int count, char *args[]){  
//code to  be executed  
} 
A virtual address is composed of the selector and offset.
 
A near pointer doesn't have explicit selector whereas far, and huge pointers have explicit selector. When you perform pointer arithmetic on the far pointer, the selector is not modified, but in case of a huge pointer, it can be modified.
 
These are the non-standard keywords and implementation specific. These are irrelevant in a modern platform.
Before going to write the c program to check whether the number is Armstrong or not, let's understand what is Armstrong number.
 
Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers.
 
Let's try to understand why 153 is an Armstrong number.

153 = (1*1*1)+(5*5*5)+(3*3*3)  
where:  
(1*1*1)=1  
(5*5*5)=125  
(3*3*3)=27  
So:  
1+125+27=153  ​

Let's see the c program to check Armstrong Number in C.
 
#include<stdio.h>  
 int main()    
{    
int n,r,sum=0,temp;    
printf("enter the number=");    
scanf("%d",&n);    
temp=n;    
while(n>0)    
{    
r=n%10;    
sum=sum+(r*r*r);    
n=n/10;    
}    
if(temp==sum)    
printf("armstrong  number ");    
else    
printf("not armstrong number");    
return 0;  
} 
  
Output :
enter the number=153
armstrong number

enter the number=5
not armstrong number
There are two possible methods to perform this task.
 
Use increment (++) and decrement (-) operator.
Example :
When x=4, x++ returns 5 and x- returns 3.​
Use conventional + or – sign.
Example :
When x=4, use x+1 to get 5 and x-1 to get 3.​
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 >.
"++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.
A loop that runs within another loop is referred to as a nested loop. The first loop is called the Outer Loop and the inside loop is called the Inner Loop. The inner loop executes the number of times defined in an outer loop.
The algorithm is created first and it contains step by step guidelines on how the solution should be. Also, it contains the steps to consider and the required calculations/operations within the program.
Yes, it works 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.
Int data type is capable of storing values between 32768 to 32767. To store 32768 a modifier has to be used with int data type and hence Long Int can be used. If there are no negative values, unsigned int can also be used.
A memory leak occurs when programmers create a memory in the heap and forget to delete it.It decreases the efficiency of the performance of the system.
while(0) means that the looping conditions will always be false, i.e., the code inside the while loop will not be executed. On the opposite, while(1) is an infinite loop. It runs continuously until coming across a break statement mentioned explicitly.
 
Note : Any non-zero integer inside the braces of the while loop will give an infinite loop. For example, while(-22) and while(24) will both yield an infinite loop.
The expression on the left of the assignment operator (=) is called an ivalue. An rvalue is an expression on the right side of the assignment operator, and it is assigned to an ivalue.
 
For instance,
int a = 25; 
int a is the ivalue in the above-mentioned example while 25 is the rvalue. While an ivalue persists beyond a single expression, the rvalue doesn’t persist beyond the expression using it.
Bit fields are variables defined with a predefined width (size) inside a structure. The general syntax of a bit field is :
 
struct {
    type [member_name] : width ;
};
 
type : Integer type, such as int and signed int, determining how a bit field’s value is interpreted.
 
member-name : Name of the bit field.
 
width : Number of bits in the bit field. Must be less than or equal to the bit width of the specified integer type.
A far pointer is a 32-bit pointer capable of accessing all the 16 segments, i.e., the whole residence memory of RAM. It can access information outside the computer memory in a given segment. To use the far pointer, it is required to :
 
Allocate the sector register to store data address in the segment, and Store another sector register within the most recent sector
The C language is commonly called the “The mother of programming languages” as it is the language that forms the bases of programming. It is a time-honoured language and has been widely used to develop some of the most significant compilers and kernels. C language is as old as the hills, and most of the modern languages are nothing but an adaptation from the C languages.
As everything has a finite potential, so the C language stands in no exception. The following are some of the drawbacks of C languages :
 
Concept of OOPs : C language prohibits the concept of OOPs as it is based on the procedural approach. (Inheritance, Polymorphism, Encapsulation, Abstraction, Data Hiding).

Run Time Checking : C language does not do the running checking which means that errors are not detected after every line of coding, but only once the complete coding is done making it inconvenient to correct the bugs

Concept of the Namespace : C language does not exhibit the property of Namespace, so there cannot be two variables with the same name in the C language program.

Lack of Exception Handling : The language doesn’t exhibit the important feature of exception handling. The feature of exception handling doesn’t allow the user to detect the errors and bugs while compiling the code.

Insufficient Level for Abstraction : C language doesn’t have a very wide data handling capacity, which poses a threat to the security of the language.
Source code : Source codes usually get a command from the programmer and these codes are responsible for instructing the computer regarding what to perform? With extension .C we can save this code in C programming.

Object code : With the extension. OBJ, we can save the object code in C programming. This is the major difference between the two codes.
We all know that in every computer we store a large amount of significant information and every time we take a lot of time in finding the key content from the large database but this random access file helps in solving this problem.
 
* It helps to find the key data quicker from a large database.
* It helps indirectly shifting to target address when there are a lot of addresses in the programming.
Fast speed : The operators and data types used in C programming are very effective and powerful that increases the speed of working. Hence it helps in fastening up the speed.

Memory management : It has a very unique feature of in build memory that can handle a large amount of data very effectively and efficiently. This helps in improving the overall performance of C programming.
Queue is a kind of data structure present in the C programming and all the data present in this queue is stored in the format called FIFO. The full form of FIFO is first-in-first-out. In every queue, the first data is available on the first line.
Yes. It is possible to print “Hello World” without semicolon in C program. Please refer below example program.
 
 
This program prints “Hello World” in console window and returns 11 which is the value of string length.
 
#include <stdio.h>
int main()
{
  if(printf(“Hello World”))
 {
  /* Do nothing */
 }
}
Segmentation fault is a fault that occurs because of illegal/invalid memory access. Illegal memory access means, When a program tries to access a memory location that is not allowed or when a program tries to access a memory location in a way that is not allowed.
strcpy( ) function copies whole content of one string into another string. Whereas, strncpy( ) function copies portion of contents of one string into another string.

If destination string length is less than source string, entire/specified source string value won’t be copied into destination string in both cases.
Yes. We can call atexit() function more than once. But, they will be executed in reverse order as a stack.
 
Example Program : 
#include <stdio.h> 
#include <stdlib.h>
 
void Exit1 (void)
{
   printf ("Exit1 function is called\n");
}
void Exit2 (void)
{
   printf ("Exit2 function is called \n");
}
 
int main (void)
{
   atexit (Exit1);
   atexit (Exit2);
   printf ("This is the end of this program.\n");
   return 0;
}
 
Output :
This is the end of this program.
Exit2 function is called
Exit1 function is called
goto statement is used to transfer the normal flow of a program to the specified label in the program. Below is the syntax for goto statement in C.
 
{
…….
goto label;
…….
…….
LABEL:
statements;
}
Header files are those which contain C function declaration and macro definitions that are to be shared between sourced files. Header files are generated with the extension .h.
 
There are two types of header files:
 
* Programmer generated a header file
* Files that come with your compiler

Syntax: #include <file>
Dynamic memory allocation is the process of memory allocation at the run time. There are a group of functions in C used to dynamic memory management i.e. calloc(), malloc(), realloc() and free().
#include <stdio.h>
int main()
{
   int x, y; 
   printf(“Input two integers (x & y) to swap\n”);
   scanf(“%d%d”, &x, &y);
   x = x + y;
   y = x – y;
   x = x – y;
   printf(“x = %d\ny = %d\n”,x,y);
   return 0;
}
Arrow operator is used to accessing elements in structure and union. It is used with a pointer variable. Arrow operator is formed by using a minus sign followed by a greater than a symbol.
 
Syntax :
(pointer_name)->(variable_name)
It is a way to convert constant from one type to another type. If there is a value of float data type then you can typecast it into other data types.
 
There are two types of typecasting in C:
 
* Implicit conversion
* Explicit conversion

Example :
#include <stdio.h>
main() {
   int sum = 17, count = 5;
   double mean;
   mean = (double) sum / count;
   printf(“Value of mean : %f\n”, mean );
}
Disadvantages of a void pointer :
 
* Pointer arithmetic is not defined for void pointer
* Void pointers can’t be dereferenced
It is referred to as a terminating null character, and is used primarily to show the end of a string value.
A linear search refers to the way a target key is being searched in a sequential data structure. Using this method, each element in the list is checked and compared against the target key, and is repeated until found or if the end of the list has been reached.
Assuming that the data to be inserted is a unique value (that is, not an existing entry in the tree), check first if the tree is empty. If it’s empty, just insert the new item in the root node. If it’s not empty, refer to the new item’s key. If it’s smaller than the root’s key, insert it into the root’s left subtree, otherwise, insert it into the root’s right subtree.
A dequeue is a double-ended queue. This is a structure wherein elements can be inserted or removed from either end.
A bubble sort is one sorting technique that can be applied to data structures such as an array. It works by comparing adjacent elements and exchanges their values if they are out of order. This method lets the smaller values “bubble” to the top of the list, while the larger value sinks to the bottom.
An AVL (Adelson-Velskii and Landis) tree is a height balance tree. These trees are binary search trees in which the height of two siblings are not permitted to differ by more than one. i.e. [Height of the left subtree – Height of right subtree] <= 1 .
Huffman’s algorithm is associated in creating extended binary trees that has minimum weighted path lengths from the given weights. It makes use of a table that contains frequency of occurrence for each data element.
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.
A translation unit is a set of files seen by the compiler.

It includes the source code under consideration and files that are included such as header files and other disk files contain C code.
<> 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.
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.
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.
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.
It is used to convert any letter to its upper case mode. Toupper() function prototype is declared in <ctype.h>. Note that this function will only convert a single character, and not an entire string.
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.
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.
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.
If (num>=0)
printf("number is positive");

else
printf ("number is negative");