C Interview Questions and Answers for Freshers

Most Asked C Interview Questions

C Interview Questions and Answers are given on this page for technical interview preparation. You can practice most asked java questions 2021-22 for freshers. We have covered C topics like Dangling Pointer, Preprocessor Directive, Dynamic Memory Allocation etc.

Page Highlights:

  • What is C?

  • Top 45 C Interview Questions.

  • Technical Interview Questions.

C Interview Questions and Answers
  1. What is a datatype in C?
  2. What is the difference between local and global variables in C?
  3. Explain about ++e and e++.
  4. Give an example for ternary operator in C.
  5. How many types of datatypes are available in C?
  6. Differentiate between constant and variable in C.
  7. Explain about a dangling pointer?
  8. Is it necessary to have a main() function in a C program?
  9. Give an example for a preprocessor directive.
  10. How will you take a sentence from a user in C?
  11. Why is C a Middle level Language?
  12. What are the key features in the C programming language?
  13. How will you print “Hello World” without a semicolon?
  14. Why is C called the Mother of all Languages?
  15. How Do You Print An Address?
  16. What is the equivalent code of the following statement in WHILE LOOP format?
  17. How is the null pointer different from a void pointer?
  18. What is a sequential access file?
  19. Compare arrays with pointers in the C programming language?
  20. List out some of the C compilers.
  21. What is recursion in C?
  22. What is the general form of function in C?
  23. When Would You Use A Pointer To A Function?
  24. What is Dynamic Memory allocation? Mention the syntax.
  25. How To Convert A Number To A String?
  26. What is the use of printf() and scanf() functions?
  27. What is a pointer in C?
  28. What is the use of a static variable in C?
  29. What Is The Heap?
  30. Is It Better To Use Malloc () Or Calloc ()?
  31. Can you tell me how to check whether a linked list is circular?
  32. What are the valid places to have the keyword “Break”?
  33. Differentiate between call by value and call by reference.
  34. Write a code to generate random numbers in C Language
  35. What do you mean by Memory Leak?
  36. Explain Local Static Variables and what is their use?
  37. How can you remove duplicates in an array?
  38. When should a far pointer be used?
  39. What is the difference between declaring a variable and defining a variable?
  40. What are rvalue and lvalue?
  41. What is the difference between void foo(void) and void foo()?
  42. What will be the output of printf(“%d”)?
  43. What is indirection?
  44. Differentiate between getch() and getche().

  45. Can I use int datatype to store 32768 value?

Technical Interview Questions

Introduction to C

C is a general purpose high-level language most popular amongst coders, it is the most compatible, easy to learn and effective programming language. It is a successor of B language that came out way back in the 70s and has been the most popular programming language ever since.

Use of C Language-

  • We can develop compilers in C language.
  • Network Drivers are also created using C language.
  • Text Editors are developed using the C language like Notepad++,gedit e.t.c.
  • Database Management System are developed using the C language like oracle database.

Top 45 C Interview Questions

What is a datatype in C?

Ans. Data Type specifies the type of data that is assigned to a variable. Each variable used in the program will be associated with a datatype. Some mostly used datatypes are:

1.int:  

  • This datatype is used to store integers. 
  • It requires 4 bytes of memory.
  • Syntax : int i;
2.float:
  • This datatype is used to store decimal numbers with single precision.
  • It requires 4 bytes of memory.
  • Syntax : float i;
3.double:
  • This datatype is used to store decimal numbers with double precision.
  • It requires 8 bytes of memory.
  • Syntax : double i;
4.char:
  • This datatype is used to store a single character.
  • It requires 1 byte of memory.
  • Syntax: char a;

What is the difference between local and global variables in C?

Ans. Local variables: The variables that are defined within the function and are accessible to that function itself are known as “local variables”.

Example :
#include <stdio.h>

void main(){

int c = 3;
printf(“%d”,c);

}

Global variables: The variables that are defined outside the function block and are accessible to any function are known as “global variables”.

Example :
#include <stdio.h>
int c = 3;


void main(){


printf(“%d”,c);

}

Explain about ++e and e++.

Ans. ++e is called pre-increment and e++ is called post-increment. Pre-increment means before assigning the value to a variable, the value will be incremented by one. Whereas Post-increment means after assigning the value to a variable, the value is incremented by one.

Example:
#include <stdio.h>
int main(){

     int e = 2;

     printf("%d\t",e++);

     printf("%d\t",e);

     printf("%d\t",++e);

     printf("%d\t",e);

     return 0;

}

Output : 2 3 4 4

Give an example for ternary operator in C.

Ans. “?:” is known as ternary operator or conditional operator. It is similar to if else control flow. And also it takes less space.

Syntax: result = condition ? ValueReturnedIfTrue : ValueReturnedIfFalse
Example:
#include <stdio.h>
int main(){

    int a = 2,b = 3;

    a>b?printf("a is greatest number"):printf("b is greatest number");

     return 0;

}

Output: b is greatest number

How many types of datatypes are available in C?

Ans. C supports two types of datatypes and those data types are again classified.

  • Primary Datatypes: These are fundamental datatypes which include int,float,char,double,void.
  • Derived Datatypes: These are derived from primary datatypes which include union,structure,array.

Differentiate between constant and variable in C.

Ans.
  • Constant : It is an identifier whose value is constant that can’t be changed.
Syntax : const float f = 5.69; In the above one, the value of f can’t be changed, it is fixed throughout the program.
  •  Variable : It is an identifier whose value can be changed in the program, it is not fixed as constant.
Syntax : float f = 5.69; In the above one, the value of f can be changed in the program, it isn’t fixed throughout the program.

Explain about a dangling pointer?

Ans. A dangling pointer is a pointer which points to some memory location that has been deleted or freed already. In simpler words, Any pointer pointing to a destroyed object or which does not contain a valid address is called a dangling pointer. If any pointer points to a memory address of a variable, after some time if the variable is deleted from memory but still if the pointer points to the same address location, it is a dangling pointer.

Example:
#include <stdio.h>

#include <stdlib.h> void main() {      int *p = (int *)malloc(sizeof(int));      // After below free call, ptr becomes a       // dangling pointer      free(p);     }

Is it necessary to have a main() function in a C program?

Ans. Yes, to execute the program, the main() function is important. The program won’t get executed without that function.

Give an example for a preprocessor directive.

Ans.  Preprocessor directives are those which start with line #. These are typically used to make the source programs easy to understand, easy to compile and easy to change.

Example :
#include <stdio.h> //preprocessor directive
 
#define END 5 //preprocessor directive

int main(){

for (int i = 0; i < END+1; i++) {

printf("%d \n",i);

}

return 0;

}

How will you take a sentence from a user in C?

Ans. In order to take a sentence from user(input), we have to use scanf(“%[^\n]%*c”,s)

Where, ^\n – takes input until a newline isn’t encountered.

  %*c – reads new line character.

   * – indicates new line character is discarded.

Why is C a Middle level Language?

Ans. A middle level language is one that binds the gap between machine level language and high level language. C language is one such programming language.  It finds its application in both, system programming (like as operating system) as well as application programming (like as spreadsheet). Middle level languages are more related to machine as well as human language. So that’s why it is called “Middle level language”.

What are the key features in the C programming language?

Ans. Features are as follows:

  • Portability: C language has no dependency on the platform.
  • Modularity: Scope of breaking bigger programs to smaller reusable modules.
  • Flexibility: The possibility of a programmer to control the language.
  • Speed: C compiles and executes with high speed when compared with other high-level languages as it comes with support for system programming and hence it .
  • Extensibility: Possibility to add new features by the programmer.

How will you print “Hello World” without a semicolon?

Ans.
#include <stdio.h> 

int main(void){

if(printf("Hello World")){

}

}

Why is C called the Mother of all Languages?

Ans. Many core concepts and data structures like arrays, lists, functions, strings, etc. were introduced through C Language. Many of the new programming languages have been developed on the basic concepts of C Language.

How Do You Print An Address?

Ans. Using the %P specification in the printf() or( fprintf() or sprintf() ) statement. This prints a void pointer (void*). This format might change from compiler to compiler.  If you have some other kind of pointer (not a void*) and you want to be very safe, cast the pointer to a void*: printf (“%Pn”, (void*) buffer);

What is the equivalent code of the following statement in WHILE LOOP format? for (int a=1; a<=100; a++) printf ("%d\n", a * a);

Ans.
int a=1;
while (a<=100) {
printf ("%d\n", a * a);
a++;
}
 

How is the null pointer different from a void pointer?

Ans.

A null pointer is basically a null value assigned to a pointer of any data type whereas a void pointer is a data type which remains void as long as an address of a data type is not assigned to it.The data type of the pointer is nothing but the type of data stored at the memory location where the pointer is pointed. When you are not sure about the type of data that is going to be stored at a particular memory location, you need to create the void pointer.Null pointer does not contain a reference to any variable/value. Hence we may state that it has a NULL as its value making it a null pointer.void pointer is always of type void *

#include<stdio.h>
 #include<stdlib.h> 
void main(){

    int a = 22;

    int *notnullpointer = &a;

    int *nullpointer1;                             // Null because there is no initialization.

    int *nullpointer2 = 0;                                              // Null because initialized with 0

    if (notnullpointer == 0) printf ("\nNot null pointer is null.");

    else printf ("\nNot null pointer is not null.");

    if (nullpointer1 == 0) printf ("\nNull pointer 1 is null.");

    else printf ("\nNull pointer 1 is not null.");

    if (nullpointer2 == 0) printf ("\nNull pointer 2 is null.");

    else printf ("\nNull pointer 2 is not null.");

    printf ("\nNot null pointer has stored the address %d.", &notnullpointer);

    printf ("\nNull pointer 1 has no valid address.");

    printf ("\nNull pointer 2 has no valid address.");

}

What is a sequential access file?

Ans. In this type of file, data is kept in sequential order if we want to read the last record of the file, we need to read all records before that record so it takes more time. When writing programs that will store and retrieve data in a file, it is possible to designate that file into different forms. 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.

Compare arrays with pointers in the C programming language?

Ans. Following are the various differences between arrays and pointers in C:
  • Definition – A pointer is a variable that stores or points to the memory address of some other variable whereas an array is a form of data structure that stores multiple, homogeneous elements at contiguous memory locations.
  • Initialization – An array can be initialized at the definition whereas the pointer can’t be done in the same way.
  • Size – an array is capable of storing multiple elements whereas a pointer can store the address of only a single variable. The total number of elements stored by arrays is determined by the array size.

List out some of the C compilers.

Ans.

C programming is a very old programming language and has a wide range of compilers available in the market. They are available in multiple operating systems. Some of them are listed below

  • AMPC
  • CCS C Compiler
  • ch
  • clang
  • Cygwin
  • Digital mars
  • GCC compiler
  • MikroC Compiler
  • Portable C Compiler, Power C, QuickC, Ritchie C Compiler, Small-C

What is recursion in C?

Ans.

In some special cases, a function can call itself and this process is called recursion. In this process, this function is called a Recursive function. Recursive function comes in two phases:

  1. Winding phase
  2. 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.
#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.

}

What is the general form of function in C?

Ans.

The function in C consists of four main sections. They are:

  • Return Type: Every return value has a data type which is defined as Return type.
  • Function Name: The name of the function is important. It must have a meaningful name that describes the operation that the function does.
  • Parameters: The input values for the function that are used to perform the required action.
  • Function Body: All the task commands compiled for performing a special task for which the function was made.
Snippet
<return_type> <function_name>( <parameter list> ){

<body of the function>

}

When Would You Use A Pointer To A Function?

Ans. Function pointers can be useful when you want to create a callback mechanism and need to pass the address of a function to another function. They can also be useful when you want to store an array of functions, to call dynamically.A function that takes function pointers says, in effect, “Part of what I do can be customized. Give me a pointer to a function, and I’ll call it when that part of the job needs to be done. That function can do its part for me.” This is known as a “callback.” It’s used a lot in graphical user interface libraries, in which the style of a display is built into the library but the contents of the display are part of the application.As a simpler example, say you have an array of character pointers (char*s), and you want to sort it by the value of the strings the character pointers point to. The standard qsort() function uses function pointers to perform that task. qsort() takes four arguments,

  • a pointer to the beginning of the array,
  • the number of elements in the array,
  • the size of each array element, and,
  •  a comparison function, and returns an int.

What is Dynamic Memory allocation? Mention the syntax.

Ans. Allocating memory to the program and its variables in runtime is the process of Dynamic Memory Allocation.The dynamic Memory Allocation process involves three functions for allocating memory and one function to free the used memory.
  • malloc() Syntax : ptr = (cast-type*) malloc(byte-size);     –   Allocates memory.
  • calloc() Syntax : ptr = (cast-type*)calloc(n, element-size);  –    Allocates memory.
  • realloc() Syntax: ptr = realloc(ptr, newsize);  –    Allocates memory.
  • free () Syntax: free(ptr)      –    Deallocates memory.

How to convert a Number to a String?

Ans.

There are a number of functions to convert numbers to many from one format to another. Some of the functions are listed below:

Function Name Purpose :

  • iota():    Converts an integer value to a string.
  • ltoa ():   Converts a long integer value to a string.
  • ultoa (): Converts an unsigned long integer value to a string.

The following functions can be used to convert floating-point values to strings:

Function Name Purpose :

  • ecvt():   Converts a double-precision floating-point value to a string without an embedded decimal point.
  • fcvt(): Same as ecvt(), but forces the precision to a specified number of digits.
  • gcvt(): Converts a double-precision floating-point value to a string with an embedded decimal point.
  • strtod(): Converts a string to a double-precision floating-point value and reports any “leftover” numbers that could not be converted.
  • strtol(): Converts a string to a long integer and reports any “leftover” numbers that could not be converted.
  • strtoul(): Converts a string to an unsigned long integer and reports any “leftover” numbers that could not be converted.

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

Ans. printf(): This function helps in printing the integer, character, float, and strings.

Following are the format specifier:

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

scanf(): The scanf() function helps in obtaining the input from the user.

What is a pointer in C?

Ans. 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 are known as the pointer variable.

What is the use of a static variable in C?

Ans. A static variable is used for a common value which is shared by all the methods and its scope is till the lifetime of the whole program. In the C programming language, static is used with global variables and functions to set their scope to the containing file.

Following are some more properties of a static variable:

  • The static variable retains its value between multiple function calls.
  • Static variables are used because the scope of the static variable is available in the entire program. So, we can access a static variable anywhere in the program.
  • The static variable is initially initialized to zero. If we update the value of a variable, then the updated value is assigned.
  • The static variable is used as a common value that is shared by all the methods.
  • The static variable is initialized only once in the memory heap to reduce memory usage.

What is the Heap?

Ans. The heap is where malloc(), calloc(), and realloc() get memory. Accessing memory from the heap is far slower than accessing it from a stack. But the other point being that heap is a bit more flexible than a stack. Getting memory from the heap is much slower than getting it from the stack. On the other hand, the heap is much more flexible than the stack. Memory can be allocated at any time and deallocated in any order. Such memory isn’t deallocated automatically; you have to call free ().Recursive data structures are almost always implemented with memory from the heap. Strings often come from there too, especially strings that could be very long at runtime. If you can keep data in a local variable (and allocate it from the stack), your code will run faster than if you put the data on the heap. Sometimes you can use a better algorithm if you use the heap—faster, or more robust, or more flexible. It’s a tradeoff.If memory is allocated from the heap, it’s available until the program ends. That’s great if you remember to deallocate it when you’re done. If you forget, it’s a problem. A “memory leak” is some allocated memory that’s no longer needed but isn’t deallocated. If you have a memory leak inside a loop, you can use up all the memory on the heap and not be able to get any more. (When that happens, the allocation functions return a null pointer.) In some environments, if a program doesn’t deallocate everything it allocated, memory stays unavailable even after the program ends.

Is It Better To Use Malloc () Or Calloc ()?

Ans. Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other. malloc() takes a size and returns a pointer to a chunk of memory at least that big. calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk of memory at least big enough to hold them all.

There’s one major difference and one minor difference between the two functions. The major difference is that malloc () doesn’t initialize the allocated memory. The first time malloc () gives you a particular chunk of memory, the memory might be full of zeros. If memory has been allocated, freed, and reallocated, it probably has whatever junk was left in it. That means, unfortunately, that a program might run in simple cases (when memory is never reallocated) but break when used harder (and when memory is reused). calloc() fills the allocated memory with all zero bits. That means that anything there you’re going to use as a char or an int of any length, signed or unsigned, is guaranteed to be zero. Anything you’re going to use as a pointer is set to all zero bits. That’s usually a null pointer, but it’s not guaranteed. Anything you’re going to use as a float or double is set to all zero bits; that’s a floating-point zero on some types of machines, but not on all. The minor difference between the two is that calloc () returns an array of objects; malloc () returns one object. Some people use calloc () to make clear that they want an array.

Can you tell me how to check whether a linked list is circular?

Ans. Create two pointers, and set both to the start of the list. Update each as follows:

while (pointer1) {
pointer1 = pointer1->next;
 
pointer2 = pointer2->next;
 
if (pointer2) pointer2=pointer2->next;
 
if (pointer1 == pointer2) {
 
print ("circular");
 
}}
If a list is circular, at some point pointer2 will wrap around and be either at the item just before pointer1, or the item before that. Either way, it’s either 1 or 2 jumps until they meet.

What are the valid places to have the keyword “Break”?

Ans. The Break keyword’s aim is to remove control from the currently running code block. Only looping and turn statements will contain it.

Differentiate between call by value and call by reference.

Ans.

Call by Value

  • Actual arguments cannot be changed and remain safe.
  • Separate memory loCopy of actual arguments are sent.
  • cations are created for actual and formal arguments.
Call by Reference
  • Operations are performed on actual arguments, hence not safe.
  • Actual and Formal arguments share the same memory space.
  • Actual arguments are passed.

Write a code to generate random numbers in C Language

Ans. Random numbers in C Language can be generated as follows:

#include 
#include 
int main()
{
int a,b;
for(a=1;a<=10;a++)
{
b=rand();
printf("%dn",b);
}
return 0;
}
OUTPUT
1987384758
2057844389
3475398489
2247357398
1435983905

What do you mean by Memory Leak?

Ans. Memory Leak occurs when a programmer allocates dynamic memory to a program but fails to free or erase the used memory after the code has been completed. If daemons and servers are included in the software, this is dangerous.

#include 
#include 
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

Explain Local Static Variables and what is their use?

Ans. A local static variable is one whose existence does not end when it is declared in a function call. It is valid for the duration of the entire curriculum. The function’s calls all 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; 
}

How can you remove duplicates in an array?

Ans. The following program will help you to remove duplicates from an array.

#include <stdio.h>
int main()
{
int n, a[100], b[100], calc = 0, i, j,count;
printf("Enter no. of elements in array");
scanf("%d", &n);
printf("Enter %d integersn", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i< n; i++) 
{
for (j = 0; j< calc; j++) 
{
if(a[i] == b[j])
break; 
}
if (j== calc)
{
b[count] = a[i];
calc++; 
}
}
printf("Array obtained after removing duplicate elementsn");
for (i = 0; i< calc; i++)
{ 
printf("%dn", b[i]);
}
return 0;
}
OUTPUT:-
Enter no. of elements in array. 5
Enter 5 integers
12
11
11
10
4
Array obtained after removing duplicate elements
12
11
10
4

When should a far pointer be used?

Ans. You can often get away with using a limited memory model for the majority of a program. There might be a few items in your small data and code segments that don’t suit you. When this occurs, you can access the remaining memory by using explicit far pointers and function declarations. A far function may exist outside of the 64KB section that most functions are crammed into in order to fit into a small-code model. You can often get away with using a limited memory model for the majority of a program. There might be a few items in your small data and code segments that don’t suit you. When this occurs, you can access the remaining memory by using explicit far pointers and function declarations. A far function may exist outside of the 64KB section that most functions are crammed into in order to fit into a small-code model.

What is the difference between declaring a variable and defining a variable?

Ans. Declaring a variable means telling the compiler its type but not allocating any memory for it. Declaring a variable and allocating space to keep it are both parts of the definition process. A variable may also be initialized when it is specified.

What are rvalue and lvalue?

Ans. In an assignment, an lvalue is the left side operant, while a rvalue is a right. You can also remember lvalue as a place. As a result, lvalue refers to a place where any value can be stored. For example, in the statement I = 20, the value 20 is to be stored in the variable i’s position or address. Rvalue is 20 in this case. Then the argument 20 = I is invalid. As 20 does not reflect any position, it will result in the compilation error “lvalue needed.”

What is the difference between void foo(void) and void foo()?

Ans. In C, void foo() denotes a function that takes an unspecified number of unspecified type arguments, while void foo(void) denotes a function that takes no arguments. In the case of void foo(), the compiler will not raise any errors if we call it foo(1,2,3). In the case of void foo, however, the compiler will generate an error (void). When calling a function in C, the caller moves all of the arguments into the stack in reverse order before calling the callee. The compiler will not evaluate the arguments passed to foo if you use foo(). In the case of foo(void), the compiler will check the number of arguments before calling the function and will raise an error if the number of arguments is incorrect.

What will be the output of printf(“%d”)?

Ans. The compiler will generate a warning but will not trigger an error if only percent d is used in printf without any variables. In this case, the compiler calculates the correct offset based on %d, but since the actual data variable is not in that measured memory location, printf will fetch the integer size value and print whatever is there (which is garbage value to us).

What is indirection?

Ans. It is direct access in C when we use the variable name to access the value. When we use a pointer to get the value of a variable, we are using indirection.

Differentiate between getch() and getche().

Ans. The only difference between the two roles is that one reads characters from the keyboard and the other does not. getch() is a function that reads characters from the keyboard without using any buffers. As a result, no data is shown on the computer. getche() uses a buffer to read characters from the keyboard. As a result, information is shown on the projector.

#include <stdio.h>
#include <stdlib.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

Can I use int datatype to store 32768 value?

Ans. No, the Integer data type does not support the range -32768 to 32767. Any value greater than that would be discarded. We have the choice of using float or long int.

Also Check:

FAQs on C Interview Questions

Name some types of searching.

Ans. Linear Search, Binary Search.

Name some types of sorting.

Ans. Quick Sort, Merge Sort, Radix Sort, Bubble Sort, Heap Sort.