August 21, 2024

Top C Programming Interview Questions for Freshers

Top C Programming Interview Questions for Freshers

Are you preparing for your first C programming interview and wondering what questions you might face? Understanding the key C interview questions for freshers can give you more clarity.

This blog is here to help you get ready with practical questions that test your real-world problem-solving skills. We’ve gathered some of the most common basic C programming interview questions that freshers often encounter.

With this guide, you’ll be well-prepared to tackle these C programming interview questions and answers for freshers and make a strong impression in your interview.

c programming beginners course desktop banner horizontal

Practice C Programming Interview Questions and Answers

Below are the top 50 C programming interview questions for freshers with answers:

1. Write a C program to swap two integers without using a third variable.

Answer:

Use arithmetic operations to swap values directly.

int a = 5, b = 10;
a = a + b;
b = a – b;
a = a – b;

2. What is the result of assigning a float value to an int variable in C? Explain with an example.

Answer:

The float value is truncated to an integer value, losing the fractional part.

float x = 5.7;
int y = x; // y will be 5

3. How can you declare a constant variable and why is it useful in C?

Answer:

Declare a constant using the const keyword, which prevents modification of the variable’s value.

const int MAX_VALUE = 100;

4. Write a C program that converts a character digit (e.g., ‘5’) into its corresponding integer value.

Answer:

Subtract the ASCII value of ‘0’ from the character to get the integer value.

char ch = ‘5’;
int num = ch – ‘0’; // num will be 5

5. Explain the difference between type conversion and type casting with an example.

Answer:

Type conversion is automatic, while type casting is explicitly forced by the programmer.

int a = 10;
float b = (float)a; // type casting from int to float

6. Write a C program to check if a number is even or odd using bitwise operators.

Answer:

Use the bitwise AND operator to check the least significant bit.

int num = 5;
if (num & 1) {
printf(“Odd\n”);
} else {
printf(“Even\n”);
}

7. What is the output of the following C code and why?

#include <stdio.h>

int main() {
int x = 10, y = 20, z = 5;
int result = x + y * z;
printf(“%d”, result); // What will be the output?
return 0;
}

Answer:

The output of the code is 110. This is because of operator precedence in C. The multiplication operator (*) has higher precedence than the addition operator (+), so y * z is evaluated first, giving 20 * 5 = 100. Then, x + 100 is evaluated, resulting in 10 + 100 = 110. Hence, the final output printed is 110.

8. Write a C program to compute the result of a logical expression: !(a > b && c < d).

Answer:

The program evaluates the logical expression and prints the result.

int a = 5, b = 3, c = 8, d = 10;
int result = !(a > b && c < d);
printf(“%d”, result); // Output will be 0 (false)

9. How would you use the increment and decrement operators to reverse the order of elements in an array?

Answer:

Use the increment and decrement operators to swap elements from start and end of the array.

int arr[] = {1, 2, 3, 4, 5};
int i = 0, j = 4;
while (i < j) {
int temp = arr[i];
arr[i++] = arr[j];
arr[j–] = temp;
}

10. Debug the following code and explain the mistake:

int a = 10, b = 5, c = 2;

int result = a / b * c;

printf(“%d”, result); // Output will be 4, but the expected output is 1

Answer:

The issue lies in operator precedence, where both division (/) and multiplication (*) have the same precedence and are evaluated from left to right.

As a result, the expression a / b * c is evaluated as (10 / 5) * 2, which gives 4 instead of the expected 1. To get the correct result, you should change the expression to a / (b * c).

11. Write a C program to find the maximum of three numbers using nested if-else statements.

Answer:

Use nested if-else statements to compare three numbers.

int a = 10, b = 15, c = 7;
if (a > b) {
if (a > c) printf(“a is the largest\n”);
else printf(“c is the largest\n”);
} else {
if (b > c) printf(“b is the largest\n”);
else printf(“c is the largest\n”);
}

12. Explain how a switch case can be used to handle multiple cases that require the same action.

Answer:

Use multiple cases without a break to combine actions.

int x = 2;
switch (x) {
case 1:
case 2:
case 3:
printf(“Number is between 1 and 3”);
break;
default:
printf(“Number is out of range”);
}

13. Write a C program to calculate the factorial of a number using a for loop.

Answer:

Use a for loop to multiply numbers in a decreasing order to find the factorial.

int n = 5;
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
printf(“Factorial: %d”, fact); // Output will be 120

14. How can you use a while loop to reverse the digits of a number in C?

Answer:

Use a while loop to extract and reverse digits until the number becomes zero.

int num = 1234, rev = 0;
while (num > 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
printf(“Reversed: %d”, rev); // Output will be 4321

15. Debug the following do-while loop code and explain the mistake:

#include <stdio.h>

int main() {
int i = 10;
do {
printf(“i is %d\n”, i);
i–;
} while (i < 0);
return 0;
}

Answer:

#include <stdio.h>
int main() {
int i = 10;
while (i > 0) { // Changing to a while loop to ensure it doesn’t run if the condition is false
printf(“i is %d\n”, i);
i–;
}
return 0;
}

The original do-while loop guarantees that the loop body will execute at least once, regardless of the initial condition. In the given code, even though the condition i < 0 is false at the start (since i is 10), the loop executes once, printing i is 10.

If this behavior is not intended, switching to a while loop ensures that the loop will not execute at all if the condition is initially false. This prevents unintended execution when the condition should prevent the loop from running.

16. Write a C program that demonstrates the use of a function that returns the largest of two numbers.

Answer:

Define a function that takes two arguments and returns the larger value.

int max(int a, int b) {
return (a > b) ? a : b;
}
int main() {
printf(“Max: %d”, max(10, 15)); // Output will be 15
}

17. What happens if a function prototype is missing in a C program?

Answer:

If a function prototype is missing, the compiler may assume incorrect types for arguments, leading to potential errors.

18. Write a C program to swap two numbers using a function and the call by value method.

Answer:

Pass the values to the function, but note that changes will not affect the original variables.

void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
swap(x, y);
printf(“x: %d, y: %d”, x, y); // Output will be x: 5, y: 10
}

19. Write a recursive function in C to calculate the nth Fibonacci number.

Answer:

A recursive function calls itself to calculate the Fibonacci sequence.

int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n – 1) + fibonacci(n – 2);
}
int main() {
printf(“Fibonacci: %d”, fibonacci(5)); // Output will be 5
}

20. Explain the scope and lifetime of variables with an example of a static variable in a function.

Answer:

Static variables retain their value across function calls and are only initialized once.

void counter() {
static int count = 0;
count++;
printf(“Count: %d\n”, count);
}
int main() {
counter(); // Output will be 1
counter(); // Output will be 2
}

21. Write a C program to reverse the elements of a one-dimensional array.

Answer:

Use a loop to swap elements from the start and end of the array.

int arr[] = {1, 2, 3, 4, 5};
int n = 5;
for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n – 1 – i];
arr[n – 1 – i] = temp;
}

22. How do you pass a two-dimensional array to a function in C?

Answer:

Pass the array by specifying the number of columns in the function prototype.

void printMatrix(int matrix[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
printf(“%d “, matrix[i][j]);
}
printf(“\n”);
}
}

23. Write a C program to perform binary search on a sorted array.

Answer:

Use a loop to repeatedly divide the array and narrow down the search range.

int binarySearch(int arr[], int size, int key) {
int left = 0, right = size – 1;
while (left <= right) {
int mid = left + (right – left) / 2;
if (arr[mid] == key) return mid;
if (arr[mid] < key) left = mid + 1;
else right = mid – 1;
}
return -1;
}

24. How would you sort an array using the bubble sort algorithm in C?

Answer:

Use nested loops to repeatedly swap adjacent elements if they are in the wrong order.

void bubbleSort(int arr[], int n) {
for (int i = 0; i < n – 1; i++) {
for (int j = 0; j < n – i – 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

25. Debug the following code snippet for initializing a multi-dimensional array.

#include <stdio.h>

int main() {
int arr[2][3] = {
{1, 2},
{4, 5, 6}
};

return 0;
}

Answer:

#include <stdio.h>

int main() {
int arr[2][3] = {
{1, 2, 3}, // The correct initialization
{4, 5, 6}
};
return 0;
}

The original code has an incorrect initialization of a multi-dimensional array. The array arr[2][3] expects each row to contain exactly 3 elements.

In the incorrect code, the first row only has 2 elements, which causes a mismatch. The corrected code ensures that both rows have 3 elements, as required by the array’s dimensions.

26. Write a C program to demonstrate pointer arithmetic by incrementing a pointer to traverse an array.

Answer:

Use a pointer to access and incrementally traverse each element in an array.

int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
for (int i = 0; i < 5; i++) {
printf(“%d “, *ptr);
ptr++;
}

27. What is the output of the following code involving pointers and arrays?

int arr[] = {10, 20, 30};
int *ptr = arr;
printf(“%d”, *(ptr + 1));

Answer:

The output of the code is 20. This code demonstrates how pointers can be used to access elements of an array. The pointer ptr is initialized to point to the first element of the array arr.

The expression *(ptr + 1) dereferences the pointer to access the element at index 1 of the array, which is 20. Hence, the output printed is 20.

28. Write a C program to dynamically allocate memory for an integer array using malloc.

Answer:

Use malloc to allocate memory and assign values to the dynamically created array.

int *arr = (int *)malloc(5 * sizeof(int));
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}

29. How do you use pointers to swap two strings in C?

Answer:

Use pointer manipulation to swap the addresses of two strings.

void swap(char **str1, char **str2) {
char *temp = *str1;
*str1 = *str2;
*str2 = temp;
}

30. Explain how to implement a pointer to a pointer and its use case in a function.

Answer:

A pointer to a pointer is used to modify the original pointer’s address within a function.

void modifyPointer(int **ptr) {
static int x = 100;
*ptr = &x;
}

31. Write a C program to count the number of vowels in a string using a loop.

Answer:

Use a loop to traverse the string and increment the count for each vowel found.

char str[] = “Hello, World!”;
int vowels = 0;
for (int i = 0; str[i] != ‘\0’; i++) {
if (str[i] == ‘a’ || str[i] == ‘e’ || str[i] == ‘i’ || str[i] == ‘o’ || str[i] == ‘u’) {
vowels++;
}
}

32. How do you concatenate two strings in C using the strcat function?

Answer:

Use strcat to append one string to another.

char str1[20] = “Hello, “;
char str2[] = “World!”;
strcat(str1, str2); // str1 now contains “Hello, World!”

33. Write a C program to reverse a string without using any standard library functions.

Answer:

Use a loop to swap characters from the start and end of the string.

char str[] = “Hello”;
int n = strlen(str);
for (int i = 0; i < n / 2; i++) {
char temp = str[i];
str[i] = str[n – i – 1];
str[n – i – 1] = temp;
}

34. How can you use pointers to compare two strings in C?

Answer:

Use pointer arithmetic to compare characters until a difference is found or the end of a string is reached.

int compareStrings(char *str1, char *str2) {
while (*str1 && (*str1 == *str2)) {
str1++;
str2++;
}
return *(unsigned char *)str1 – *(unsigned char *)str2;
}

35. Debug the following code that attempts to read a string using scanf.

#include <stdio.h>

int main() {
char str[20];
scanf(“%s”, str); // This code will work, but it won’t read strings with spaces
printf(“You entered: %s\n”, str);
return 0;
}

Answer:

#include <stdio.h>
int main() {
char str[20];
scanf(“%19[^\n]”, str); // This allows the input to include spaces up to 19 characters
printf(“You entered: %s\n”, str);
return 0;
}

The issue with the original code is that scanf(“%s”, str); only reads a word until a space is encountered. To read a string that includes spaces, the format specifier should be modified.

In the corrected code, scanf(“%19[^\n]”, str); reads up to 19 characters or until a newline character is encountered, allowing the input string to include spaces. The width specifier (19) ensures that no more than 19 characters are read, preventing buffer overflow.

36. Write a C program to store and display the details of a student using a structure.

Answer:

Define a structure and use it to store and display student information.

struct Student {
char name[50];
int age;
float marks;
};
int main() {
struct Student s1 = {“John”, 20, 85.5};
printf(“Name: %s, Age: %d, Marks: %.2f”, s1.name, s1.age, s1.marks);
}

37. How do you pass a structure to a function in C by value? Provide an example.

Answer:

Pass the structure as a parameter to the function, making a copy of the structure.

void display(struct Student s) {
printf(“Name: %s, Age: %d, Marks: %.2f”, s.name, s.age, s.marks);
}

38. Write a C program that demonstrates the difference between structures and unions.

Answer:

Structures allocate separate memory for each member, while unions share memory among members.

struct Example {
int x;
char y;
};
union ExampleUnion {
int x;
char y;
};

39. Explain how to create an array of structures in C and provide a simple example.

Answer:

Declare an array of structures and initialize each element.

struct Student {
char name[50];
int age;
float marks;
} students[3] = {{“John”, 20, 85.5}, {“Alice”, 22, 90.0}, {“Bob”, 19, 78.0}};

40. Write a C program to dynamically allocate memory for a structure using malloc.

Answer:

Use malloc to allocate memory and assign values to the structure.

struct Student *s = (struct Student *)malloc(sizeof(struct Student));
s->age = 20;

[/su_note]

41. Write a C program to open a file, write some text, and close the file.

Answer:

Use fopen, fprintf, and fclose to perform file operations.

FILE *file = fopen(“test.txt”, “w”);
if (file != NULL) {
fprintf(file, “Hello, World!”);
fclose(file);
}

42. How do you read a string from a file in C using fgets?

Answer:

Use fgets to read a line of text from the file.

char buffer[100];
FILE *file = fopen(“test.txt”, “r”);
if (file != NULL) {
fgets(buffer, 100, file);
fclose(file);
}

43. Write a C program to count the number of lines in a text file.

Answer:

Use a loop to read each line and increment the count.

int count = 0;
char c;
FILE *file = fopen(“test.txt”, “r”);
if (file != NULL) {
while ((c = fgetc(file)) != EOF) {
if (c == ‘\n’) count++;
}
fclose(file);
}

44. How can you write binary data to a file in C using fwrite?

Answer:

Use fwrite to write binary data from a buffer to a file.

int data[] = {1, 2, 3, 4, 5};
FILE *file = fopen(“data.bin”, “wb”);
if (file != NULL) {
fwrite(data, sizeof(int), 5, file);
fclose(file);
}

45. Explain how to handle file errors in C when performing file I/O operations.

Answer:

Check the return value of file operations and use perror or strerror to print the error message.

FILE *file = fopen(“nonexistent.txt”, “r”);
if (file == NULL) {
perror(“Error opening file”);
}

46. Write a macro to calculate the square of a number in C.

Answer:

Use the #define directive to create a macro that calculates the square.

#define SQUARE(x) ((x) * (x))

47. How do you use conditional compilation to include code only if a macro is defined?

Answer:

Use #ifdef and #endif to conditionally compile code based on the presence of a macro.

#define DEBUG
#ifdef DEBUG
printf(“Debug mode is on\n”);
#endif

48. Explain the difference between standard and user-defined macros with an example.

Answer:

Standard macros are predefined by the compiler, while user-defined macros are created by the programmer.

#define PI 3.14
#define AREA(r) (PI * (r) * (r))

49. Write a C program to include a header file using the #include directive.

Answer:

Use #include to add a header file to your program.

#include <stdio.h>
#include “myheader.h”

50. Debug the following macro code and explain the mistake:

#include <stdio.h>

#define MULTIPLY(a, b) a * b

int main() {
int result = MULTIPLY(2 + 3, 4 + 5); // What will be the result?
printf(“Result: %d\n”, result);
return 0;
}

Answer:

The macro lacks parentheses around the argument, leading to incorrect results.

#include <stdio.h>
#define MULTIPLY(a, b) ((a) * (b)) // Corrected macro with parentheses around arguments
int main() {
int result = MULTIPLY(2 + 3, 4 + 5); // This will now produce the correct result
printf(“Result: %d\n”, result); // Correct result will be 45
return 0;
}

The mistake in the original macro is the lack of parentheses around the macro arguments. Without parentheses, the expression MULTIPLY(2 + 3, 4 + 5) is expanded to 2 + 3 * 4 + 5, which follows operator precedence rules and evaluates to 19 instead of the intended 45.

By adding parentheses around the macro parameters (((a) * (b))), the macro expansion correctly respects the intended grouping of operations, ensuring the correct result of 45.

Final Words

Getting ready for an interview can feel overwhelming, but going through these C programming fresher interview questions can help you feel more confident. This guide focuses on the kinds of C developer interview questions for fresher roles that you’re likely to face.

Don’t forget to practice the basic C coding interview questions too! With the right preparation, you’ll ace your C programming interview and take that important step in your career.


Frequently Asked Questions

1. What are the most common interview questions for C programming?

Common interview questions for C programming often focus on data types, pointers, memory management, arrays, strings, and control structures like loops and conditional statements.

2. What are the important C programming topics freshers should focus on for interviews?

Freshers should focus on understanding pointers, memory allocation (dynamic memory), arrays, string manipulation, functions, and basic algorithms.

3. How should freshers prepare for C programming technical interviews?

Freshers should practice writing and debugging code, understand core concepts deeply, and solve sample interview questions regularly to build confidence.

4. What strategies can freshers use to solve C programming coding questions during interviews?

Freshers should break down problems into smaller parts, write clear and modular code, use comments to explain logic, and thoroughly test their code with different inputs.

5. Should freshers prepare for advanced C programming topics in interviews?

Yes, depending on the job role, freshers might need to know advanced topics like pointers to pointers, file handling, data structures (linked lists, stacks, queues), and bitwise operations.


Explore More C Programming Resources

Explore More Interview Questions

zen-class vertical-ad
author

Thirumoorthy

Thirumoorthy serves as a teacher and coach. He obtained a 99 percentile on the CAT. He cleared numerous IT jobs and public sector job interviews, but he still decided to pursue a career in education. He desires to elevate the underprivileged sections of society through education

Subscribe

Thirumoorthy serves as a teacher and coach. He obtained a 99 percentile on the CAT. He cleared numerous IT jobs and public sector job interviews, but he still decided to pursue a career in education. He desires to elevate the underprivileged sections of society through education

Subscribe