c language interview questions
c language interview questions
Functions
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
struct Student {
char name[50];
int age;
float gpa;
};
struct Address {
char city[50];
int zipCode;
};
struct Student {
char name[50];
int age;
struct Address address;
};
union Data {
int intVal;
float floatVal;
char charVal;
};
18. How do you pass an array to a function? In C, when you pass an array to a function,
you actually pass a pointer to its first element. Here's an example:
c
void printArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printArray(arr, size);
return 0;
}
19. Explain the concept of pointers in C. Pointers are variables that store memory addresses
of other variables. They are powerful tools that enable dynamic memory allocation, array
manipulation, and efficient function arguments passing. Here’s a basic pointer example:
c
int x = 10;
int *ptr = &x; // ptr stores the address of x
printf("%d", *ptr); // Output: 10
20. What are pointer arithmetic and its uses? Pointer arithmetic allows the manipulation of
the addresses stored in pointers. It supports operations like increment (++), decrement (--),
addition (+), and subtraction (-). This is useful for iterating through arrays.
c
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i)); // Outputs the array elements
}
Operators
21. What are the different types of operators in C? C has several operators:
• Arithmetic: +, -, *, /, %
• Relational: ==, !=, >, <, >=, <=
• Logical: &&, ||, !
• Bitwise: &, |, ^, ~, <<, >>
• Assignment: =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
• Miscellaneous: sizeof, ? : (ternary), & (address of), * (pointer dereference)
22. Explain the difference between the && and || operators. The && (logical AND)
operator returns true if both operands are true. The || (logical OR) operator returns true if at
least one operand is true. They are used to combine multiple conditions in logical
expressions.
23. What is the sizeof operator and how is it used? The sizeof operator returns the size,
in bytes, of its operand. It is used to determine the memory size required for a data type or
variable.
c
int a = 10;
printf("Size of a: %zu bytes\n", sizeof(a)); // Outputs the size of int
24. How does the ternary (conditional) operator work in C? The ternary operator (? :) is
a shorthand for the if-else statement. It evaluates a condition and returns one value if true,
and another if false.
c
int a = 10, b = 20;
int max = (a > b) ? a : b;
printf("Maximum: %d\n", max); // Outputs: Maximum: 20
25. What is the difference between ++a and a++? ++a is the prefix increment operator,
which increments a before using its value. a++ is the postfix increment operator, which
increments a after using its value.
c
int a = 5;
printf("%d\n", ++a); // Outputs: 6
printf("%d\n", a++); // Outputs: 6
printf("%d\n", a); // Outputs: 7
Conditional Branching
26. Explain the if-else statement in C. The if-else statement allows conditional
execution of code blocks based on whether a condition is true or false.
c
int a = 10;
if (a > 5) {
printf("a is greater than 5");
} else {
printf("a is not greater than 5");
}
27. How does the switch statement work and provide an example? The switch statement
allows multi-way branching based on the value of an expression. It executes the
corresponding case block and can use break to exit the block.
c
int day = 3;
switch (day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
default: printf("Invalid day"); break;
}
c
int a = 10, b = 20;
if (a > b) {
printf("a is greater");
} else {
if (a == b) {
printf("a and b are equal");
28. How does the switch statement work and provide an example?
The switch statement allows a variable to be tested against a list of values, each with a
corresponding action. It provides a way to execute different parts of code based on the value
of a variable.
c
#include <stdio.h>
int main() {
int number = 2;
switch (number) {
case 1:
printf("Number is 1\n");
break;
case 2:
printf("Number is 2\n");
break;
case 3:
printf("Number is 3\n");
break;
default:
printf("Number is not 1, 2, or 3\n");
break;
}
return 0;
}
c
#include <stdio.h>
int main() {
int number = 20;
if (number > 0) {
if (number % 2 == 0) {
printf("Number is positive and even\n");
} else {
printf("Number is positive and odd\n");
}
} else {
printf("Number is not positive\n");
}
return 0;
}
The break statement is used to exit a loop or switch statement prematurely. It stops the
execution of the loop or switch and transfers control to the statement immediately following
the loop or switch.
The default case in a switch statement is executed if none of the case labels match the
value of the switch expression. It acts as a catch-all for values not explicitly handled.
Looping
The for loop is used to repeat a block of code a certain number of times. It includes an
initialization, a condition, and an increment/decrement.
c
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
34. Describe the do-while loop and how it differs from the while loop.
• Answer: The do-while loop is similar to the while loop, but with a key difference:
the do-while loop executes the code block at least once before checking the
condition. The syntax is:
c
do {
// code block to be executed
} while (condition);
The condition is evaluated after executing the code block. If the condition is true, the code
block is executed again. This continues until the condition becomes false.
35. How do you use the break and continue statements in loops?
• Answer: The break statement is used to terminate the loop or switch statement
prematurely. When encountered, the control immediately exits the loop. The
continue statement, on the other hand, skips the remaining code inside the current
iteration of the loop and proceeds with the next iteration. Example:
c
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // exit the loop when i is 5
}
if (i % 2 == 0) {
continue; // skip the current iteration if i is even
}
printf("%d ", i);
}
Advanced Topics
• Answer: A linked list is a linear data structure where elements are stored in nodes,
and each node points to the next node in the sequence. It is implemented using
structures in C:
c
struct Node {
int data;
struct Node* next;
};
• Answer: A stack can be implemented using arrays by defining an array and a top
pointer:
c
#define MAX 100
int stack[MAX];
int top = -1;
void push(int x) {
if (top == MAX - 1) {
printf("Stack Overflow\n");
} else {
stack[++top] = x;
}
}
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
return stack[top--];
}
}
• Answer: A binary tree is a hierarchical data structure where each node has at most
two children, referred to as the left and right child. Traversal methods include:
o In-order (Left, Root, Right)
o Pre-order (Root, Left, Right)
o Post-order (Left, Right, Root) Example of in-order traversal:
c
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
• Answer: The malloc function allocates memory of a specified size and returns a
pointer to the allocated memory. The free function deallocates the memory
previously allocated by malloc, calloc, or realloc.
c
int* ptr = (int*)malloc(10 * sizeof(int)); // Allocate memory for 10
integers
if (ptr == NULL) {
printf("Memory allocation failed\n");
} else {
// Use the allocated memory
free(ptr); // Deallocate memory
}
Problem-Solving
• Answer:
c
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
printf("The largest element is %d\n", findLargest(arr, n));
return 0;
}
41. Write a C program to find the largest element in an array.
c
#include <stdio.h>
int main() {
int n, i;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);
return 0;
}
c
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
while (h > l) {
if (str[l++] != str[h--]) {
return false;
}
}
return true;
}
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
if (isPalindrome(str)) {
printf("%s is a palindrome.\n", str);
} else {
printf("%s is not a palindrome.\n", str);
}
return 0;
}
Example:
c
#include <stdio.h>
int main() {
ulong num = 123456789;
printf("num: %lu\n", num);
return 0;
}
Logical operators are used to perform logical operations on expressions. They return either
true (non-zero) or false (zero) based on the result of the logical operation.
Example:
c
#include <stdio.h>
int main() {
int a = 5, b = 10, c = 0;
if (a && b) {
printf("Both a and b are non-zero.\n");
}
if (a || c) {
printf("Either a or c is non-zero.\n");
}
if (!c) {
printf("c is zero.\n");
}
return 0;
}
Bitwise operators are used to perform operations on individual bits of integers. They are
mainly used in low-level programming, such as system programming and embedded systems.
Example:
c
#include <stdio.h>
int main() {
int a = 5, b = 3;
return 0;
}
File operations in C involve opening, reading, writing, and closing files using the standard
I/O functions.
Example:
c
#include <stdio.h>
int main() {
FILE *file;
char str[100];
return 0;
}
48. What is a preprocessor directive and provide an example?
Example:
c
#include <stdio.h>
#define PI 3.14159
int main() {
printf("Value of PI: %f\n", PI);
return 0;
}
Macros are defined using the #define preprocessor directive and are used to create constants
or inline functions.
Example:
c
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main() {
int num = 5;
printf("Square of %d: %d\n", num, SQUARE(num));
return 0;
}
Basic C Programming Questions
Copy
int a = 5;
printf("%d", a++);
Answer: 5
10. Output of the code:
c
Copy
int a = 5;
printf("%d", ++a);
Answer: 6
Control Flow Questions
Copy
if (num % 2 == 0) printf("Even");
else printf("Odd");
13. Output of the code:
c
Copy
int x = 10;
if (x = 20) printf("True");
else printf("False");
Answer: True (assignment operator = is used instead of ==).
14. Program to find the largest of three numbers:
c
Copy
Copy
int i = 0;
while (i < 5) {
printf("%d ", i);
i++;
}
Answer: 0 1 2 3 4
16. Difference between while and do-while:
o while checks the condition before execution.
o do-while checks the condition after execution.
17. Program to print first 10 natural numbers:
c
Copy
Copy
Copy
int a = 0, b = 1, c;
for (int i = 0; i < n; i++) {
printf("%d ", a);
c = a + b;
a = b;
b = c;
}
Functions Questions
21. Function in C:
o A block of code that performs a specific task.
22. Difference between declaration and definition:
o Declaration: int func();
o Definition: int func() { return 0; }
23. Default return type of a function:
o int (if not specified).
24. Output of the code:
c
Copy
void print() {
printf("Hello, World!");
}
int main() {
print();
return 0;
}
Answer: Hello, World!
25. Recursion example (factorial):
c
Copy
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
26. Difference between call by value and call by reference:
Call by value: Passes a copy of the variable.
o
o Call by reference: Passes the address of the variable.
27. Output of the code:
c
Copy
void change(int x) {
x = 10;
}
int main() {
int x = 5;
change(x);
printf("%d", x);
return 0;
}
Answer: 5 (call by value).
28. Program to swap two numbers using pointers:
c
Copy
Copy
int func() {
static int x = 0;
x++;
return x;
}
int main() {
printf("%d ", func());
printf("%d ", func());
return 0;
}
Answer: 1 2 (static variable retains its value).
Copy
int sum = 0;
for (int i = 0; i < n; i++) sum += arr[i];
34. Output of the code:
c
Copy
Copy
Copy
Copy
Pointers Questions
Copy
int x = 10;
int *p = &x;
printf("%d", *p);
Answer: 10
43. Difference between *p and p:
o *p is the value at the address stored in p.
o p is the address stored in the pointer.
44. Program to swap two numbers using pointers:
c
Copy
Copy
Copy
int len = 0;
while (*str != '\0') {
len++;
str++;
}
49. Difference between int *p and int **p:
o int *p is a pointer to an integer.
o int **p is a pointer to a pointer to an integer.
50. Output of the code:
c
Copy
int x = 10;
int *p = &x;
int **q = &p;
printf("%d", **q);
Answer: 10
Copy
struct Point {
int x;
int y;
};
52. Difference between structure and union:
o Structure allocates memory for all members.
o Union allocates memory for the largest member only.
53. Program to store and display student details:
c
Copy
struct Student {
char name[50];
int roll;
};
struct Student s = {"John", 1};
printf("%s %d", s.name, s.roll);
54. Output of the code:
c
Copy
Copy
union Data {
int x;
float y;
};
union Data d;
d.x = 10;
printf("%d", d.x);
57. Output of the code:
c
Copy
union Data d;
d.x = 10;
printf("%d", d.x);
Answer: 10
58. Difference between struct and typedef:
o struct defines a new data type.
o typedef creates an alias for an existing data type.
59. Program to demonstrate nested structures:
c
Copy
struct Address {
char city[50];
};
struct Person {
char name[50];
struct Address addr;
};
60. Output of the code:
c
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
typedef struct {
int x;
int y;
} Point;
Point p = {1, 2};
86. Difference between const and volatile:
o const makes a variable read-only.
o volatile indicates that a variable's value may change unexpectedly.
87. Output of the code:
c
Copy
#define SQUARE(x) (x * x)
printf("%d", SQUARE(2 + 3));
Answer: 11 (due to operator precedence).
88. Purpose of #define:
o Used to define macros.
89. Program to demonstrate #ifdef:
c
Copy
#define DEBUG
#ifdef DEBUG
printf("Debug mode");
#else
printf("Release mode");
#endif
90. Output of the code:
c
Copy
#ifdef DEBUG
printf("Debug mode");
#else
printf("Release mode");
#endif
Answer: Release mode (if DEBUG is not defined).
Miscellaneous Questions
Copy
Copy
int x = 5, y = 10;
printf("%d", x > y ? x : y);
Answer: 10
94. Difference between strcpy() and strncpy():
o strcpy() copies the entire string.
o strncpy() copies up to n characters.
95. Program to sort an array using bubble sort:
c
Copy
Copy
int x = 5;
int *p = &x;
int **q = &p;
printf("%d", **q);
Answer: 5
97. Difference between exit() and return:
o exit() terminates the entire program.
o return exits the current function.
98. Program to find GCD of two numbers:
c
Copy
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
printf("%d", a);
99. Output of the code:
c
Copy
int x = 5;
printf("%d", x << 1);
Answer: 10 (left shift by 1 multiplies by 2).
100. Difference between memcpy() and memmove():
o memcpy() does not handle overlapping memory regions.
o memmove() handles overlapping memory regions.