C Interview Questions And Answers


C is a structured, procedural programming language widely used to code OS and applications worldwide.

Many versions of Unix-based OS are written in C. C has also been standardized as a part of POSIX (portable operating system interface). It is commonly used on computer architectures that range from the largest supercomputers to the smallest microcontrollers.

C has become the most widely used programming language with compilers available for almost every modern computer. 

C is an imperative procedural language that supports structured programming, lexical variable scope, and recursion with a static type system. The language was designed to be compiled to provide low-level memory access. It efficiently maps to machine instructions, all with minimal runtime support. 

If you write a standards-compliant C program with portability in mind, you can easily compile it for various computer platforms and OS with few changes to its source code.

Characteristics of C

Before heading towards the C interview questions and answers, here is a quick brief about some basic characteristics of the language:

  • In C, all the executable is written in subroutines (also called functions) where functional parameters are passed a value. You must also note that arrays are passed as pointers, that is, the address of the first item in the array, while Pass-by-reference is simulated by explicitly passing pointers to the thing being referenced.
  • C program source text is in free format. It uses “;” as a statement separator and “{}” for grouping blocks of statements. 
  • The programming language has a fixed number of keywords, including a full set of control primitives. For example, if/else, for, do/while and switch.
  • You can perform more than one assignment in a single statement.
  • The function return value can be ignored.
  • Function and data pointers permit Adhoc runtime polymorphism. Also, you can define variables within a function.
  • It supports recursion as a function may call itself.
  • Data typing is static, and all data has a type. However, implicit conversions are possible.
  • Low-level access to computer memory is possible.
  • Procedures with an untitled return value (void) are a special case of function.
  • A preprocessor performs macro definitions and source code file inclusions.

Although C can’t perform specific functions like other languages, like object orientations and garbage collection, but you emulate these by external libraries like the GLib Object System or the Boehm garbage collector).

1 . Why is C popular as a mother language?

C is popular as a mother language becaus most of the compilers and JVMs are written in C language. Most of the languages which are developed after C language have borrowed heavily from it like C++, Python, Rust, javascript, etc. It introduces new core concepts like arrays, functions, file handling which are in these languages.

2 . Why is C a mid-level programming language?

C is a mid-level programming language because it binds the low level and high -level programming language. We can use C language as a System programming to develop the operating system as well as an Application programming to generate menu driven customer driven billing systems.

3 . Who is the founder of the C language?

Dennis Ritchie.

4 . When was the C language developed?

C language was developed in 1972 at bell laboratories of AT&T.

5 . What are the features of the C language?

The main features of C language are below:

  • Simple: C is a simple language because it follows the structured approach, i.e., a program is broken into parts
  • Portable: C is highly portable means that once you write the program, you can run it on any machine with little or no modifications.
  • Mid Level: C is a mid-level programming language as it combines the low- level language with the features of the high-level language.
  • Structured: C is a structured language as the C program is broken into parts.
  • Fast Speed: C language is very fast as it uses a powerful set of data types and operators.
  • Memory Management: C provides an inbuilt memory function that saves the memory and improves the efficiency of our program.
  • Extensible: C is an extensible language as it can adopt new features in the future.

6 . What is the use of printf() and scanf() functions?

printf(): The printf() function works to print the integer, character, float and string values onto the screen.

Following are the format specifier:

  • %d: It is a format specifier that works to print an integer value.
  • %s: It is a format specifier that works to print a string.
  • %c: It is a format specifier that works to display a character value.
  • %f: It is a format specifier that works to display a floating point value.

scanf(): The scanf() function works to take input from the user.

7 . What is the difference between the local variable and global variable in C?

Following are the differences between a local variable and global variable:

Basis for comparisonLocal variableGlobal variable
DeclarationA variable which is declared inside a function or block is known as a local variable.A variable which is declared outside a function or block is known as a global variable.
ScopeThe scope of a variable is available within a function in which they are declared.The scope of a variable is available throughout the program.
AccessVariables can be accessed only by those statements inside a function in which they are declared.Any statement in the entire program can access variables.
LifeLife of a variable is created when the function block is entered and destroyed on its exit.Life of a variable exists until the program is executed.
StorageVariables are stored in a stack unless specified.The compiler decides the storage location of a variable.

8 . What is the use of the function in C?

Uses of C function are:

  • C functions works to avoid rewriting the same code again and again in our program.
  • C functions can be called any number of times from any place of our program.
  • When a program is divided into functions, then any part of our program can easily be tracked.
  • C functions provide the reusability concept, i.e., it breaks the big task into smaller tasks so that it makes the C program more understandable.

9 . What is an array in C?

An Array is a group of similar types of elements. It has a contiguous memory location. It makes the code optimized, easy to traverse and easy to sort. The size and type of arrays cannot be changed after its declaration.

Arrays are of two types:

  • One-dimensional array: One-dimensional array is an array that stores the elements one after the another.

Syntax:

  1. data_type array_name[size];  
  • Multidimensional array: Multidimensional array is an array that contains more than one array.

Syntax:

  1. data_type array_name[size];  

Example of an array:

 int arr[5]={1,2,3,4,5}; //an array consists of five integer values.  
   for(int i=0;i<5;i++)  
   {  
       printf("%d ",arr[i]);  
   }  
    return 0;  
}  
Output:
1 2 3 4 5
  

10 . What is a pointer in C?

A pointer is a variable that refers to the address of a value. It makes the code optimized and makes the performance fast. Whenever a variable is declared inside a program, then the system allocates some memory to a variable. The memory contains some address number. The variables that hold this address number is the pointer variable.

For example:

  1. Data_type *p;  

The above syntax tells that p is a pointer variable that holds the address number of a given data type value.

Example of pointer

#include <stdio.h>  
int main()  
{  
   int *p; //pointer of type integer.  
   int a=5;  
   p=&a;  
   printf("Address value of 'a' variable is %u",p);  
    return 0;  
}  
Output:
Address value of 'a' variable is 428781252

11 . What is the usage of the pointer in C?

  • Accessing array elements: Pointers works in traversing through an array of integers and strings. The string is an array of characters which you can terminate by a null character ‘\0’.
  • Dynamic memory allocation: Pointers works in allocation and deallocation of memory during the execution of a program.
  • Call by Reference: The pointers works to pass a reference of a variable to another function.
  • Data Structures like a tree, graph, linked list, etc.: The pointers are helpful to construct different data structures like tree, graph, linked list, etc.

12 . What is a NULL pointer in C?

A pointer that doesn’t refer to any address of value but NULL is a NULL pointer. When we assign a ‘0’ value to a pointer of any type, then it becomes a Null pointer.

13 . What is a far pointer in C?

A pointer which can access all the 16 segments (whole residence memory) of RAM is a far pointer. A far pointer is a 32-bit pointer that obtains information outside the memory in a given section.

14 . What is a dangling pointer in C?

  • If a pointer is pointing to any memory location, but meanwhile another pointer deletes the memory occupied by the first pointer while the first pointer still points to that memory location, the first pointer will be a dangling pointer. This problem is popular as a dangling pointer problem.
  • A Dangling pointer arises when an object is deleted without modifying the value of the pointer. The pointer points to the deallocated memory.

15 . What is pointer to pointer in C?

In case of a pointer to pointer concept, one pointer refers to the address of another pointer. The pointer to pointer is a chain of pointers. Generally, the pointer contains the address of a variable. The pointer to pointer contains the address of the first pointer. Let’s understand this concept through an example:

#include <stdio.h>  
 int main()  
{  
    int a=10;  
    int *ptr,**pptr; // *ptr is a pointer and **pptr is a double pointer.  
    ptr=&a;  
    pptr=&ptr;  
    printf("value of a is:%d",a);  
    printf("\n");  
    printf("value of *ptr is : %d",*ptr);  
    printf("\n");  
    printf("value of **pptr is : %d",**pptr);  
    return 0;  
} 

In the above example, pptr is a double pointer pointing to the address of the ptr variable and ptr points to the address of ‘a’ variable.

16 . What is static memory allocation?

  • In case of static memory allocation, you can allocate memory 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.
  • You can allocate the static memory using the static keyword.
  • You can implement the static memory using stacks or heaps.
  • The pointer works to access the variable present in the static memory.
  • The static memory is faster than dynamic memory.
  • In static memory, you need more memory space to store the variable.

17 . What is dynamic memory allocation?

  • In case of dynamic memory allocation, you allocate memory at runtime and memory can increase while executing the program. It is in the linked list.
  • The malloc() or calloc() function works to allocate the memory at the runtime.
  • An allocation or deallocation of memory is at the execution time of a program.
  • You don’t need dynamic pointers to access the memory.
  • You can implement the dynamic memory using data segments.
  • You require less memory space to store the variable.

For example:

int *p= malloc(sizeof(int)*10);
  

The above example allocates the memory at runtime.

18 . What functions are for dynamic memory allocation in C language?

  1. malloc()
    1. The malloc() function works to allocate the memory during the execution of the program.
    2. It does not initialize the memory but carries the garbage value.
    3. It returns a null pointer if it could not be able to allocate the requested space.
  2. Syntax
    1. ptr = (cast-type*) malloc(byte-size) // allocating the memory using malloc() function.  
  3. calloc()
    1. The calloc() is the same as malloc() function, but the only difference is that it initializes the memory with zero value.
  4. Syntax
    1. ptr = (cast-type*)calloc(n, element-size);// allocating the memory using calloc() function.  
  5. realloc()
    1. The realloc() function is to reallocate the memory to the new size.
    2. If sufficient space is not available in the memory, then you can allocate the new block to accommodate the existing data.
  6. Syntax
    1. ptr = realloc(ptr, newsize); // updating the memory size using realloc() function.  
  7. In the above syntax, you allocate ptr to a new size.free():The free() function releases the memory allocated by either calloc() or malloc() function.
  8. Syntax
    1. free(ptr); // memory frees using free() function.  

The above syntax releases the memory from a pointer variable ptr.

19 . What is the structure?

  • The structure is a user-defined data type that allows storing multiple types of data in a single unit. It occupies the sum of the memory of all members.
  • You can acess the structure members only through structure variables.
  • Structure variables accessing the same structure but the memory allocated for each variable will be different.

Syntax of structure

struct structure_name  
{  
  Member_variable1;  
 Member_variable2  
.  
.  
}[structure variables];

20 . What is a union?

  • The union is a user-defined data type that allows storing multiple types of data in a single unit. However, it doesn’t occupy the sum of the memory of all members. It holds the memory of the largest member only.
  • In union, we can access only one variable at a time as it allocates one common space for all the members of a union.

Syntax of union

union union_name  
{  
Member_variable1;  
Member_variable2;  
.  
.  
Member_variable n;  
}[union variables];

21 . What is an auto keyword in C?

In C, every local variable of a function is popular as an automatic (auto) variable. Variables which are inside the function block are local variable. The local variables are also popular as an auto variable. It is optional to use an auto keyword before the data type of a variable. If you store no value in the local variable, then it consists of a garbage value.

22 . What is the purpose of the sprintf() function?

The sprintf() stands for “string print.” The sprintf() function does not print the output on the console screen. It transfers the data to the buffer. It returns the total number of characters present in the string.

Syntax

int sprintf ( char * str, const char * format, ... );

23 . What is ANSI in C?

ANSI, or American National Standard Institute, is an organization that maintains computer languages, data safety, data encoding, etc.

24 . What is a token in C?

A token is an identifier that can be a keyword, constant, operator, a string literal, etc. It is also the smallest unit in a program in C.

25 . What is recursion in C programming?

When a function calls itself, the process is known as recursion, and the function is known as a recursive function. It has two functions, the winding phase, and the unwinding phase.

26 . What is the nested structure in C programming?

It is a structure that contains an element of another structure as its member. Basically, A nested structure is a structure within a structure. It is done the same way structure members are declared in a function.

27 . What is the difference between formal and actual parameters in C?

The parameters sent from the main function to subdivided functions are actual parameters. The parameters declared at subdivided functions are formal parameters.

28 . How to declare a function in C?

A function in C can be declared as:

return_type function_name(formal parameter list)
{
function_body;
}

29 . What is the difference between call by value and call by reference in C?

Actual arguments remain safe and can not be changed in the call by value in C. The operators are not safe as they perform on actual parameters.

In the call by value, actual segments are not passed, and a copy of the segment is sent, but in the call by reference, actual arguments are passed.

For call by value, separate memory locations are created, and for the call by reference, they share the same memory space.

30 . Can you write a program to generate random numbers in C?

Yes, I can generate random numbers in C with the help of the rand() function. Here is how:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
printf(“The number is: %d”, rand());
printf(“\n The number is: %d”, rand());
printf(“\n The number is: %d”, rand());
getch();
}
The output will be:
The number is: 455
The number is: 15648
The number is: 23212

31 . What are storage class specifiers in C?

Storage class specifiers in C are extern, static, register, and auto.

32 . What is typecasting in C?

Generally, when one data type is converted into another data type, the process is typecasting.

33 . What do you understand by enumerations in C?

An enumeration in C is a user-defined data type widely known as an enum. It has constant integers and integrals, which have names assigned by the user. It is used when a user needs a variable with a set of values.

34 . What is the ternary operator in C?

The conditional operator is the conditional operator in the C language. It is denoted as (?:).

35 . What is a preprocessor in C?

The C preprocessor is a software program that works to process a source file before compilation. Header files, conditional compilation, line control, macro expansion, etc. can be included in a preprocessor.

36 . What is the difference between lvalue and rvalue in C?

The expression that is present on the right side of the assignment operator is the rvalue. It is assigned to lvalue which is on the left side of the assignment operator. 

The lvalue represents a variable and not a constant.

37 . How can we store a negative integer?

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 -5

38 . Differentiate between getch() and getche().

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

39 . Explain toupper() with an example.

toupper() is a function 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



40 . Can I create a customized Head File in C language?

It is possible to create a new header file. Create a file with function prototypes that works in the program. Include the file in the ‘#include’ section in its name.

41 . What do you mean by Memory Leak?

Memory Leak is a situation where a programmer allocates dynamic memory to the program but fails to free or delete the used memory after the completion of the code. This is harmful if daemons and servers is in the program.

#include<stdio.h>
#include<stdlib.h>
int main()
{
     int* ptr;
     int n, i, sum = 0;
     n = 5;
     printf("Enter the number of elements: %dn", n);
     ptr = (int*)malloc(n * sizeof(int));
     if (ptr == NULL)
     {
            printf("Memory not allocated.n");
            exit(0);
     }
     else
     {
            printf("Memory successfully allocated using malloc.n");
            for (i = 0; i<= n; ++i)
            {
                  ptr[i] = i + 1;
             }
             printf("The elements of the array are: ");
             for (i = 0; i<=n; ++i)
            {
                  printf("%d, ", ptr[i]);
            }
     }
     return 0;
}



//Output

Enter the number of elements: 5

Memory successfully allocated using malloc.

The elements of the array are: 1, 2, 3, 4, 5,

42 . Explain the # pragma directive.

The following points explain the Pragma Directive.

  • This is a preprocessor directive that works 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.

43 . What is a Bubble Sort Algorithm? Explain with a program.

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. 

The following code executes Bubble Sort.

int main()
{
      int array[100], n, i, j, swap;
      printf("Enter number of elementsn");
      scanf("%d", &n);
      printf("Enter %d Numbers:n", n);
      for(i = 0; i<n; i++)
           scanf("%d", &array[i]);
           for(i = 0 ; i<n - 1; i++)
           {
                 for(j = 0 ; j < n-i-1; j++) { if(array[j]>array[j+1])
                       {
                               swap=array[j];
                               array[j]=array[j+1];
                               array[j+1]=swap;
                       }
                 }
           }
           printf("Sorted Array:n");
           for(i = 0; i < n; i++)
                 printf("%dn", array[i]);
           return 0;
}



44 . What is typedef in C?

In C programming, typedef is a keyword that defines an alias for an existing type. Whether it is an integer variable, function parameter, or structure declaration, typedef will shorten the name.

Syntax:

typedef <existing-type> <alias-name>

Here,

  • The existing type is already given a name. 
  • alias name is the new name for the existing variable.

45 . What are loops and how can we create an infinite loop in C?

Loops works to execute a block of statements repeatedly. The statement which is to be repeated will be executed n times inside the loop until the given condition is reached. There are two types of loops Entry controlled and Exit controlled loops in C programming language. An Infinite loop is a piece of code that lacks a functional exit. So, it repeats indefinitely. There can be only two things when there is an infinite loop in the program. One it was designed to loop endlessly until the condition is met within the loop. Another can be wrong or unsatisfied break conditions in the program.

Below is the program for infinite loop in C:

// C program for infinite loop 
// using for, while, do-while
#include <stdio.h>
  
// Driver code
int main()
{
  for (;;) 
  {
    printf("Infinite-loop\n");
  }
    
  while (1) 
  {
    printf("Infinite-loop\n");
  }
    
  do 
  {
    printf("Infinite-loop\n");
  } while (1);
    
  return 0;
}

46 . What is the difference between type casting and type conversion?

Type CastingType Conversion
The data type is converted to another data type by a programmer with the help of a casting operator.The data type is converted to another data by a compiler.
It can be applied to both compatible data types as well as incompatible data types.Type conversion can only be applied to only compatible data types.
In Type casting in order to cast the data type into another data type, a caste operator is neededIn type conversion, there is no need for a casting operator.
Type casting is more efficient and reliable.Type conversion is less efficient and less reliable than type casting.
Type casting takes place during the program design by the programmer.Type conversion is done at compile time.
Syntax: destination_data_type = (target_data_type) variable_to_be_converted;Syntax: int a = 20; float b; b = a; // a = 20.0000

47 . What are header files and their uses?

C language has numerous libraries which contain predefined functions to make programming easier. Header files contain predefined standard library functions. All header files must have a ‘.h’ extension. Header files contain function definitions, data type definitions, and macros which you import with the help of the preprocessor directive ‘#include’. Preprocessor directives instruct the compiler that these files are needed to be processed before the compilation. 

There are two types of header files i.e, User-defined header files and Pre-existing header files. For example, if our code needs to take input from the user and print desired output to the screen then ‘stdio.h’ header file must be included in the program as #include<stdio.h>. Also, this header file contains functions like scanf() and printf() which works to take input from the user and print the content.

48 . What is the difference between macro and functions?

A macro is a name of a block of C statements as a preprocessor directive. Macro is defined with the preprocessor directive. Macros are pre-processed which means that all the macros are preprocessed before the compilation of our program. However, functions are not preprocessed but compiled.

MacroFunction
Macros are preprocessed.Functions are compiled.
Code length is increased using macro.Code length remains unaffected using function.
Execution speed using a macro is faster.Execution speed using function is slower.
The macro name is replaced by the macro value before compilation.Transfer of control takes place during the function call.
Macro doesn’t check any Compile-Time Errors.Function check Compile-time errors.

49 . Write a program to check prime numbers in C Programming?

#include<stdio.h>      
#include<conio.h>      
void main()      
{      
int n,i,m=0,flag=0;    //declaration of variables.  
clrscr();    //It clears the screen.  
printf("Enter the number to check prime:");      
scanf("%d",&n);      
m=n/2;      
for(i=2;i<=m;i++)      
{      
if(n%i==0)      
{      
printf("Number is not prime");      
flag=1;      
break;    //break keyword used to terminate from the loop.  
}      
}      
if(flag==0)      
printf("Number is prime");      
getch();    //It reads a character from the keyword.  
}

50 . Write a program to check palindrome numbers in C Programming?

#include<stdio.h>    
#include<conio.h>    
main()    
{    
int n,r,sum=0,temp;    
clrscr();    
printf("enter the number=");    
scanf("%d",&n);    
temp=n;    
while(n>0)    
{    
r=n%10;    
sum=(sum*10)+r;    
n=n/10;    
}    
if(temp==sum)    
printf("palindrome number ");    
else    
printf("not palindrome");    
getch();    
}