C Programming Coding Questions and Answers

Published: October 27, 2025 | Reading Time: 7 minutes

Overview

"Programming isn't about typing code, it's about learning how to think."

If you've ever wondered how to truly master coding logic, C programming is the best place to start. Known as the "mother of all programming languages," C builds the foundation every developer stands on—from writing your first printf() statement to understanding how systems actually work under the hood.

This comprehensive guide covers C Programming Coding Questions and Answers for beginners, intermediate programmers, and advanced programmers who want to practice problem-solving and prepare for interviews with confidence.

What You'll Learn


What is C Programming?

C is a universal, high-level programming language that supports the generation of low-level code by incorporating both low-level (assembly) features and high-level concepts. It was developed by Dennis Ritchie in 1972 at Bell Labs.

Key Characteristics of C


Basic C Questions Asked in Interview for Beginner Level

Before discussing more complex problem-solving, mastering the basics is essential. Basic C Programming Coding Questions and Answers are invaluable for building a strong foundation.

These basic C interview questions test your logic, precision, and comfort level with the building blocks of C. They're about clarity, confidence, and clean thinking.

1. What is C programming, and why is it widely used?

Answer:

C is a general-purpose, procedural programming language that provides low-level access to memory, making it efficient and fast. C is widely used because:

2. Write a program to print "Hello, World!"

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

Output:

Hello, World!

Explanation:

The program imports the stdio.h file, which provides functions for input and output. The main() function marks the entry point into the program. The printf() function prints the string "Hello, World!" to the console, followed by a new line (\n). The statement return 0; indicates successful program execution.

3. What are the basic data types in C?

C offers several fundamental data types to represent different kinds of data:

Data Type Description Example Declaration Typical Size
int Used to store integer values int a = 10; Typically 2 or 4 bytes
float Used for single-precision floating-point numbers float b = 3.14; Usually 4 bytes
char Used to store a single character char c = 'A'; Typically 1 byte
double Used for double-precision floating-point numbers double d = 3.14159; Typically 8 bytes

Example Code:

#include <stdio.h>

int main() {
    // Integer data type
    int age = 25;
    
    // Floating point data type
    float height = 5.9;
    
    // Double precision floating point data type
    double pi = 3.14159265358979;
    
    // Character data type
    char grade = 'A';
    
    // Printing values
    printf("Age: %d\n", age);
    printf("Height: %.1f feet\n", height);
    printf("Value of Pi: %.14lf\n", pi);
    printf("Grade: %c\n", grade);
    
    return 0;
}

Output:

Age: 25
Height: 5.9 feet
Value of Pi: 3.14159265358979
Grade: A

4. Explain the difference between = and == operators in C

Answer:

Understanding this distinction is crucial for writing correct conditional statements and avoiding common programming errors.

5. What are the different types of loops in C?

Answer:

C provides three types of loops:

  1. for loop: Used when the number of iterations is known beforehand
  2. while loop: Evaluates the condition before execution and continues looping as long as the condition is true
  3. do-while loop: Executes the loop body at least once, then checks the condition after each iteration

6. Write a program to find the sum of two numbers

#include <stdio.h>

int main() {
    int num1, num2, sum;
    printf("Enter two numbers: ");
    scanf("%d %d", &num1, &num2);
    sum = num1 + num2;
    printf("Sum: %d\n", sum);
    return 0;
}

Output:

Enter two numbers: 5 7
Sum: 12

Explanation:

The program uses scanf() to read two numbers from the user, stores them in variables num1 and num2, calculates their sum, and prints the result using printf().

7. Swap two numbers without using a third variable

#include <stdio.h>

int main() {
    int a = 5, b = 10;
    a = a + b;
    b = a - b;
    a = a - b;
    printf("After swapping: a = %d, b = %d\n", a, b);
    return 0;
}

Output:

After swapping: a = 10, b = 5

8. Write a program to swap two numbers using pointers

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 10, y = 20;
    swap(&x, &y);
    printf("x: %d, y: %d\n", x, y);
    return 0;
}

Output:

x: 20, y: 10

Explanation:

The swap() function takes two pointers as arguments. By passing the addresses of variables x and y using the & operator, the function can directly modify their values in memory. The * operator dereferences the pointers to access and swap the actual values.

9. What is an Armstrong number, and how do you check if a number is Armstrong in C?

Definition:

An Armstrong number equals the sum of its digits, each raised to the power of the number of digits. Example: 153 is an Armstrong number because 1³ + 5³ + 3³ = 153.

#include <stdio.h>
#include <math.h>

int isArmstrong(int num) {
    int sum = 0, temp = num, digits = 0;
    
    // Count the number of digits
    while (temp != 0) {
        digits++;
        temp /= 10;
    }
    
    temp = num;
    
    // Calculate sum of digits raised to power of digit count
    while (temp != 0) {
        int digit = temp % 10;
        sum += pow(digit, digits);
        temp /= 10;
    }
    
    return sum == num;
}

int main() {
    int n = 153;
    
    if (isArmstrong(n))
        printf("%d is an Armstrong number.\n", n);
    else
        printf("%d is not an Armstrong number.\n", n);
    
    return 0;
}

10. How do you check if a number is an Automorphic number in C?

Definition:

An Automorphic number is a number whose square ends with the same digits as the number itself. Example: 76 is automorphic because 76² = 5776, which ends with 76.

#include <stdio.h>

int isAutomorphic(int num) {
    int square = num * num;
    int temp = num;
    
    // Compare digits from the end
    while (temp > 0) {
        if (temp % 10 != square % 10)
            return 0;  // Not Automorphic
        temp /= 10;
        square /= 10;
    }
    
    return 1;  // Automorphic number
}

int main() {
    int n = 76;
    
    if (isAutomorphic(n))
        printf("%d is an Automorphic number.\n", n);
    else
        printf("%d is not an Automorphic number.\n", n);
    
    return 0;
}

11. What is a Perfect Number? Write a C program to check for a perfect number

Definition:

A Perfect number is a positive integer that equals the sum of its proper divisors (excluding itself). Example: 28 is perfect because 1 + 2 + 4 + 7 + 14 = 28.

#include <stdio.h>

int isPerfect(int num) {
    int sum = 0;
    
    // Find sum of proper divisors
    for (int i = 1; i < num; i++) {
        if (num % i == 0)
            sum += i;
    }
    
    return sum == num;
}

int main() {
    int n = 28;
    
    if (isPerfect(n))
        printf("%d is a Perfect number.\n", n);
    else
        printf("%d is not a Perfect number.\n", n);
    
    return 0;
}

12. How do you find the Greatest Common Divisor (GCD) of two numbers in C?

Definition:

The GCD (or HCF) of two numbers is the largest number that divides both numbers without remainder. The Euclidean algorithm is the most efficient method.

#include <stdio.h>

int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int main() {
    int x = 36, y = 60;
    printf("GCD of %d and %d is %d\n", x, y, gcd(x, y));
    return 0;
}

13. How do you compute the Least Common Multiple (LCM) of two numbers in C?

Formula:

LCM(a, b) = (a × b) / GCD(a, b)

#include <stdio.h>

int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int lcm(int a, int b) {
    return (a * b) / gcd(a, b);
}

int main() {
    int k = 12, l = 18;
    printf("LCM of %d and %d is %d\n", k, l, lcm(k, l));
    return 0;
}

14. Write a C program to calculate the factorial of a number

Definition:

Factorial of n (n!) is the multiplication of all positive numbers up to n. Example: 5! = 5 × 4 × 3 × 2 × 1 = 120.

#include <stdio.h>

unsigned long long factorial(int n) {
    unsigned long long result = 1;
    
    for (int i = 2; i <= n; i++)
        result *= i;
    
    return result;
}

int main() {
    int n = 5;
    printf("Factorial of %d is %llu\n", n, factorial(n));
    return 0;
}

15. How do you find the sum of the digits of a number in C?

#include <stdio.h>

int sumOfDigits(int n) {
    int sum = 0;
    
    while (n > 0) {
        sum += n % 10;  // Add last digit
        n /= 10;        // Remove last digit
    }
    
    return sum;
}

int main() {
    int num = 12345;
    printf("Sum of digits of %d is %d\n", num, sumOfDigits(num));
    return 0;
}

16. How do you find all prime factors of a number in C?

Definition:

Prime factors are prime numbers that divide a number evenly without remainder.

#include <stdio.h>

void printPrimeFactors(int n) {
    printf("Prime factors: ");
    
    // Print number of 2s that divide n
    while (n % 2 == 0) {
        printf("2 ");
        n /= 2;
    }
    
    // Print odd prime factors
    for (int i = 3; i * i <= n; i += 2) {
        while (n % i == 0) {
            printf("%d ", i);
            n /= i;
        }
    }
    
    // If n is prime and greater than 2
    if (n > 2)
        printf("%d", n);
    
    printf("\n");
}

int main() {
    int n = 56;
    printPrimeFactors(n);
    return 0;
}

17. How can you determine the roots of a quadratic equation in C?

Formula:

For equation ax² + bx + c = 0, roots are calculated using the quadratic formula.

#include <stdio.h>
#include <math.h>

int main() {
    double a = 1, b = -3, c = 2;
    double discriminant = b * b - 4 * a * c;
    
    if (discriminant > 0) {
        // Two distinct real roots
        double root1 = (-b + sqrt(discriminant)) / (2 * a);
        double root2 = (-b - sqrt(discriminant)) / (2 * a);
        printf("Roots are real and different: %.2lf, %.2lf\n", root1, root2);
    }
    else if (discriminant == 0) {
        // Two equal real roots
        double root = -b / (2 * a);
        printf("Roots are real and same: %.2lf\n", root);
    }
    else {
        // Complex roots
        double realPart = -b / (2 * a);
        double imagPart = sqrt(-discriminant) / (2 * a);
        printf("Roots are complex: %.2lf + %.2lfi, %.2lf - %.2lfi\n", 
               realPart, imagPart, realPart, imagPart);
    }
    
    return 0;
}

C Code Questions and Answers for Intermediate Level

Intermediate-level C Programming Coding Questions and Answers challenge you to apply fundamental concepts. At this stage, you need strong understanding of variables, loops, functions, arrays, pointers, memory management, and file handling.

1. Difference Between malloc() and calloc()

Both malloc() and calloc() are used for dynamic memory allocation, but they differ in initialization and arguments:

Feature malloc() calloc()
Memory Initialization Uninitialized (garbage values) Initialized to zero
Number of Arguments One (size in bytes) Two (number of blocks, size of each)
Use Case General-purpose allocation Zero-initialized arrays
Function Signature void *malloc(size_t size) void *calloc(size_t num, size_t size)
Performance Faster (no initialization) Slower (zero initialization)

Choosing Between Them:

If zero initialization is important, use calloc(). Otherwise, malloc() is more efficient for general-purpose allocation.

2. Write a program to reverse a string

#include <stdio.h>
#include <string.h>

void reverse(char str[]) {
    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;
    }
}

int main() {
    char str[] = "Hello";
    reverse(str);
    printf("Reversed string: %s\n", str);
    return 0;
}

Output:

Reversed string: olleH

Explanation:

The reverse() function calculates string length using strlen(). A for loop iterates from start to middle, swapping characters from beginning and end using a temporary variable.

3. What is recursion in C? Provide an example

Definition:

Recursion is when a function calls itself to solve a problem.

#include <stdio.h>

int factorial(int n) {
    if (n == 0) return 1;  // Base case
    return n * factorial(n - 1);  // Recursive case
}

int main() {
    int num = 5;
    printf("Factorial: %d\n", factorial(num));
    return 0;
}

Output:

Factorial: 120

Explanation:

The factorial() function has a base case (n == 0 returns 1) and a recursive case that multiplies n by factorial(n-1). For factorial(5), it calculates 5 × 4 × 3 × 2 × 1 = 120.

4. Check Whether a Number is Prime

#include <stdio.h>
#include <stdbool.h>

bool isPrime(int n) {
    if (n <= 1)
        return false;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    if (isPrime(num))
        printf("%d is a prime number.\n", num);
    else
        printf("%d is not a prime number.\n", num);
    return 0;
}

Output:

Enter a number: 11
11 is a prime number.

5. Find the nth Fibonacci Number using Recursion

#include <stdio.h>

int fibonacci(int n) {
    if (n <= 1)
        return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
    int n;
    printf("Enter the value of n: ");
    scanf("%d", &n);
    printf("Fibonacci(%d) = %d\n", n, fibonacci(n));
    return 0;
}

Output:

Enter the value of n: 6
Fibonacci(6) = 8

6. What is the difference between while, do-while, and for loops?

Answer:

7. What is recursion, and how is it different from iteration?

Answer:

Recursion: A function calls itself to solve a problem. Useful for factorial calculation, Fibonacci sequences, and tree traversals. Consumes more stack memory.

Iteration: Uses loops to repeatedly execute code. Generally more efficient in execution speed and memory usage.

8. What is an array, and how is it different from a linked list?

Answer:

Array:

Linked List:

9. What is an inversion in an array and how can you count it in C?

Definition:

An inversion is a pair (i, j) where arr[i] > arr[j] and i < j. It indicates how far an array is from being sorted.

#include <stdio.h>

int countInversions(int arr[], int n) {
    int count = 0;
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (arr[i] > arr[j]) 
                count++;
        }
    }
    return count;
}

int main() {
    int arr[] = {8, 4, 2, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Total Inversions: %d\n", countInversions(arr, n));
    return 0;
}

10. How do you perform a circular rotation of an array in C?

#include <stdio.h>

void rightRotate(int arr[], int n, int k) {
    k = k % n;  // Handle cases where k > n
    
    for (int i = 0; i < k; i++) {
        int last = arr[n - 1];
        
        // Shift elements to the right
        for (int j = n - 1; j > 0; j--)
            arr[j] = arr[j - 1];
        
        arr[0] = last;
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = 5, k = 2;
    
    rightRotate(arr, n, k);
    
    printf("Array after circular rotation: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    
    return 0;
}

11. How can you find the transpose of a rectangular array in C?

Definition:

Transpose flips rows into columns.

#include <stdio.h>

int main() {
    int rows = 2, cols = 3;
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };
    int transpose[3][2];
    
    // Compute transpose
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            transpose[j][i] = matrix[i][j];
        }
    }
    
    // Print transposed matrix
    printf("Transpose of matrix:\n");
    for (int i = 0; i < cols; i++) {
        for (int j = 0; j < rows; j++) {
            printf("%d ", transpose[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}

12. How do you perform a spiral traversal of a matrix in C?

Definition:

Spiral traversal prints matrix elements layer by layer in clockwise direction.

#include <stdio.h>

int main() {
    int n = 3;
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    
    int top = 0, bottom = n - 1;
    int left = 0, right = n - 1;
    
    printf("Spiral traversal: ");
    
    while (top <= bottom && left <= right) {
        // Left to right along top row
        for (int i = left; i <= right; i++)
            printf("%d ", matrix[top][i]);
        top++;
        
        // Top to bottom along right column
        for (int i = top; i <= bottom; i++)
            printf("%d ", matrix[i][right]);
        right--;
        
        // Right to left along bottom row
        if (top <= bottom) {
            for (int i = right; i >= left; i--)
                printf("%d ", matrix[bottom][i]);
            bottom--;
        }
        
        // Bottom to top along left column
        if (left <= right) {
            for (int i = bottom; i >= top; i--)
                printf("%d ", matrix[i][left]);
            left++;
        }
    }
    
    printf("\n");
    return 0;
}

13. How do you find the maximum element in an array using max-heap concept?

#include <stdio.h>

void buildMaxHeap(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        int current = i;
        
        // Heapify up
        while (current > 0 && arr[(current - 1) / 2] < arr[current]) {
            // Swap with parent
            int temp = arr[current];
            arr[current] = arr[(current - 1) / 2];
            arr[(current - 1) / 2] = temp;
            
            current = (current - 1) / 2;
        }
    }
}

int main() {
    int arr[] = {10, 30, 20, 50, 40};
    int n = 5;
    
    buildMaxHeap(arr, n);
    
    printf("Maximum element using max-heap: %d\n", arr[0]);
    return 0;
}

14. How do you reverse the elements of an array in C?

#include <stdio.h>

void reverseArray(int arr[], int n) {
    int start = 0, end = n - 1;
    
    while (start < end) {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        
        start++;
        end--;
    }
}

int main() {
    int arr[] = {5, 10, 15, 20, 25};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    reverseArray(arr, n);
    
    printf("Reversed array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    
    return 0;
}

Output:

Reversed array: 25 20 15 10 5

15. Write a program to implement Bubble Sort in C

#include <stdio.h>

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;
            }
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    bubbleSort(arr, n);
    
    printf("Sorted array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    
    return 0;
}

Output:

Sorted array: 11 12 22 25 34 64 90

16. Write a program using Binary Search in C

#include <stdio.h>

int binarySearch(int arr[], int n, int key) {
    int low = 0, high = n - 1;
    
    while (low <= high) {
        int mid = (low + high) / 2;
        
        if (arr[mid] == key) {
            return mid;
        } else if (arr[mid] < key) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    
    return -1;
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);
    int key = 30;
    
    int result = binarySearch(arr, n, key);
    
    if (result != -1)
        printf("Element found at index: %d\n", result);
    else
        printf("Element not found\n");
    
    return 0;
}

Output:

Element found at index: 2

17. Write a program to implement Merge Sort in C

#include <stdio.h>

void merge(int arr[], int l, int m, int r) {
    int n1 = m - l + 1;
    int n2 = r - m;
    
    int L[n1], R[n2];
    
    for (int i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (int j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];
    
    int i = 0, j = 0, k = l;
    
    while (i < n1 && j < n2) {
        if (L[i] <= R[j])
            arr[k++] = L[i++];
        else
            arr[k++] = R[j++];
    }
    
    while (i < n1)
        arr[k++] = L[i++];
    
    while (j < n2)
        arr[k++] = R[j++];
}

void mergeSort(int arr[], int l, int r) {
    if (l < r) {
        int m = l + (r - l) / 2;
        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);
        merge(arr, l, m, r);
    }
}

int main() {
    int arr[] = {12, 11, 13, 5, 6, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    mergeSort(arr, 0, n - 1);
    
    printf("Sorted array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    
    return 0;
}

Output:

Sorted array: 5 6 7 11 12 13

18. Implement Quick Sort in C

#include <stdio.h>

int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = low - 1;
    
    for (int j = low; j <= high - 1; j++) {
        if (arr[j] <= pivot) {
            i++;
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    
    int temp = arr[i + 1];
    arr[i + 1] = arr[high];
    arr[high] = temp;
    
    return i + 1;
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int main() {
    int arr[] = {10, 7, 8, 9, 1, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    quickSort(arr, 0, n - 1);
    
    printf("Sorted array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    
    return 0;
}

Output:

Sorted array: 1 5 7 8 9 10

19. Write a program to implement Heap Sort using heapify in C

#include <stdio.h>

void heapify(int arr[], int n, int i) {
    int largest = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;
    
    if (left < n && arr[left] > arr[largest])
        largest = left;
    
    if (right < n && arr[right] > arr[largest])
        largest = right;
    
    if (largest != i) {
        int temp = arr[i];
        arr[i] = arr[largest];
        arr[largest] = temp;
        
        heapify(arr, n, largest);
    }
}

void heapSort(int arr[], int n) {
    // Build max heap
    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(arr, n, i);
    
    // Extract elements from heap
    for (int i = n - 1; i >= 0; i--) {
        int temp = arr[0];
        arr[0] = arr[i];
        arr[i] = temp;
        
        heapify(arr, i, 0);
    }
}

int main() {
    int arr[] = {12, 11, 13, 5, 6, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    heapSort(arr, n);
    
    printf("Sorted array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    
    return 0;
}

Output:

Sorted array: 5 6 7 11 12 13

20. Count inversions in an array using Merge Sort in C

#include <stdio.h>

int mergeAndCount(int arr[], int l, int m, int r) {
    int n1 = m - l + 1;
    int n2 = r - m;
    
    int L[n1], R[n2];
    
    for(int i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for(int j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];
    
    int i = 0, j = 0, k = l, inv_count = 0;
    
    while(i < n1 && j < n2) {
        if(L[i] <= R[j]) {
            arr[k++] = L[i++];
        } else {
            arr[k++] = R[j++];
            inv_count += (n1 - i);
        }
    }
    
    while(i < n1) arr[k++] = L[i++];
    while(j < n2) arr[k++] = R[j++];
    
    return inv_count;
}

int mergeSortAndCount(int arr[], int l, int r) {
    int inv_count = 0;
    if(l < r) {
        int m = l + (r - l) / 2;
        inv_count += mergeSortAndCount(arr, l, m);
        inv_count += mergeSortAndCount(arr, m + 1, r);
        inv_count += mergeAndCount(arr, l, m, r);
    }
    return inv_count;
}

int main() {
    int arr[] = {1, 20, 6, 4, 5};
    int n = sizeof(arr)/sizeof(arr[0]);
    
    int inv_count = mergeSortAndCount(arr, 0, n - 1);
    
    printf("Number of inversions: %d\n", inv_count);
    return 0;
}

Output:

Number of inversions: 5

C Programming Language Questions and Answers for Advanced Level

Advanced-level C programming questions test your understanding at a deeper level and expose you to problems relevant to systems programming and high-performance applications.

1. Explain file handling in C

Answer:

File handling in C involves reading from and writing to files using built-in functions. It's necessary for persistent data storage and file system operations.

Functions for File Handling in C:

Function Description Syntax
fopen() Opens a file for reading, writing, or appending FILE *fopen(const char *filename, const char *mode);
fclose() Closes the file opened with fopen() int fclose(FILE *stream);
fread() Reads data from a file size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
fwrite() Writes data to a file size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
fgetc() Reads a single character from a file int fgetc(FILE *stream);
fputc() Writes a single character to a file int fputc(int ch, FILE *stream);

2. Write a program to implement binary search using recursion

#include <stdio.h>

int binarySearch(int arr[], int low, int high, int key) {
    if (low <= high) {
        int mid = (low + high) / 2;
        if (arr[mid] == key) return mid;
        if (arr[mid] > key) return binarySearch(arr, low, mid - 1, key);
        return binarySearch(arr, mid + 1, high, key);
    }
    return -1;
}

int main() {
    int arr[] = {2, 3, 4, 10, 40};
    int n = 5;
    int key = 10;
    int result = binarySearch(arr, 0, n - 1, key);
    printf("Element found at index: %d\n", result);
    return 0;
}

Output:

Element found at index: 3

Explanation:

For the sorted array {2, 3, 4, 10, 40} with key 10:

  1. Initial search range: index 0 to 4
  2. Middle element at index 2 is 4 (less than 10)
  3. Search right half: index 3 to 4
  4. Middle element at index 3 is 10 (matches key)
  5. Returns index 3

3. Explain undefined behaviour in C and provide an example

Answer:

Undefined behavior occurs when code uses constructs not specified by the C standard. Results are unpredictable and can include crashes, security vulnerabilities, or nondeterministic output.

Example:

#include <stdio.h>

int main() {
    int x;
    printf("%d\n", x);  // Using uninitialized variable
    return 0;
}

The variable x is declared but not initialized. Its value is indeterminate, making the output unpredictable.

4. Write a program to implement a stack using linked lists

Definition:

A stack is a linear data structure following Last In, First Out (LIFO) principle.

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

struct Stack {
    struct Node* top;
};

void initStack(struct Stack* s) {
    s->top = NULL;
}

int isEmpty(struct Stack* s) {
    return s->top == NULL;
}

void push(struct Stack* s, int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = s->top;
    s->top = newNode;
}

int pop(struct Stack* s) {
    if (isEmpty(s)) {
        printf("Stack Underflow\n");
        return -1;
    }
    struct Node* temp = s->top;
    int poppedData = temp->data;
    s->top = s->top->next;
    free(temp);
    return poppedData;
}

void display(struct Stack* s) {
    struct Node* current = s->top;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

int main() {
    struct Stack stack;
    initStack(&stack);
    
    push(&stack, 10);
    push(&stack, 20);
    push(&stack, 30);
    
    printf("Stack contents: ");
    display(&stack);
    
    printf("Popped: %d\n", pop(&stack));
    
    printf("Stack contents after pop: ");
    display(&stack);
    
    return 0;
}

Output:

Stack contents: 30 20 10
Popped: 30
Stack contents after pop: 20 10

5. Find the second largest element in an array

#include <stdio.h>

int main() {
    int arr[] = {12, 34, 10, 6, 40};
    int largest = arr[0], second = arr[0];
    
    for (int i = 1; i < 5; i++) {
        if (arr[i] > largest) {
            second = largest;
            largest = arr[i];
        } else if (arr[i] > second && arr[i] != largest) {
            second = arr[i];
        }
    }
    
    printf("Second Largest: %d\n", second);
    return 0;
}

Output:

Second Largest: 34

6. What are pointers in C, and how do they differ from arrays?

Answer:

Pointer:

Array:

7. Explain the concept of function pointers with an example

Answer:

A function pointer is a pointer that points to a function. It enables dynamic function calls and allows functions to be passed as arguments to other functions.

Use Cases:

8. What are structures in C, and how do they differ from arrays?

Answer:

Structure:

Array:

9. What is a palindrome, and how can we check if a string is a palindrome in C?

Definition:

A palindrome reads the same forward and backward.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int isPalindrome(char str[]) {
    int i = 0;
    int j = strlen(str) - 1;
    
    while (i < j) {
        if (tolower(str[i]) != tolower(str[j]))
            return 0;  // Not a palindrome
        i++;
        j--;
    }
    return 1;  // Is a palindrome
}

int main() {
    char str[] = "Level";
    
    if (isPalindrome(str))
        printf("\"%s\" is a palindrome.\n", str);
    else
        printf("\"%s\" is not a palindrome.\n", str);
    
    return 0;
}

10. What is an anagram, and how can we check if two strings are anagrams in C?

Definition:

Two strings are anagrams if they contain the same characters at the same frequency (ignoring case).

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int isAnagram(char str1[], char str2[]) {
    int count[256] = {0};
    
    if (strlen(str1) != strlen(str2))
        return 0;
    
    for (int i = 0; str1[i]; i++) {
        count[tolower(str1[i])]++;
        count[tolower(str2[i])]--;
    }
    
    for (int i = 0; i < 256; i++)
        if (count[i] != 0)
            return 0;
    
    return 1;
}

int main() {
    char str1[] = "Listen";
    char str2[] = "Silent";
    
    if (isAnagram(str1, str2))
        printf("\"%s\" and \"%s\" are anagrams.\n", str1, str2);
    else
        printf("\"%s\" and \"%s\" are not anagrams.\n", str1, str2);
    
    return 0;
}

11. How do we count the frequency of characters in a string in C?

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "programming";
    int freq[256] = {0};
    
    // Count frequency
    for (int i = 0; str[i]; i++)
        freq[(int)str[i]]++;
    
    // Print frequencies
    printf("Character frequencies:\n");
    for (int i = 0; i < 256; i++)
        if (freq[i] > 0)
            printf("%c : %d\n", i, freq[i]);
    
    return 0;
}

12. How can we remove spaces and non-alphabetical characters from a string in C?

#include <stdio.h>
#include <ctype.h>

int main() {
    char str[] = "C programming 101!";
    char result[100];
    int j = 0;
    
    // Copy only alphabetic characters
    for (int i = 0; str[i]; i++)
        if (isalpha(str[i]))
            result[j++] = str[i];
    
    result[j] = '\0';
    
    printf("Filtered string: %s\n", result);
    return 0;
}

13. How can we replace a substring in a string in C?

#include <stdio.h>
#include <string.h>

void replaceSubstring(char str[], char old[], char new[]) {
    char buffer[200];
    char *pos = strstr(str, old);
    
    if (pos) {
        int index = pos - str;
        str[index] = '\0';
        strcpy(buffer, str);
        strcat(buffer, new);
        strcat(buffer, pos + strlen(old));
        strcpy(str, buffer);
    }
}

int main() {
    char str[100] = "Hello World!";
    replaceSubstring(str, "World", "C Programming");
    printf("Updated string: %s\n", str);
    return 0;
}

14. How can we find the first non-repeating character in a string in C?

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "programming";
    int freq[256] = {0};
    
    // Count frequency
    for (int i = 0; str[i]; i++)
        freq[(int)str[i]]++;
    
    // Find first character with frequency 1
    for (int i = 0; str[i]; i++) {
        if (freq[(int)str[i]] == 1) {
            printf("First non-repeating character: %c\n", str[i]);
            break;
        }
    }
    
    return 0;
}

15. How do you print a pyramid pattern using a for loop in C?

#include <stdio.h>

int main() {
    int n = 5;
    
    for (int i = 1; i <= n; i++) {
        // Print spaces
        for (int j = 1; j <= n - i; j++)
            printf(" ");
        
        // Print stars
        for (int k = 1; k <= (2 * i - 1); k++)
            printf("*");
        
        printf("\n");
    }
    
    return 0;
}

Output:

    *
   ***
  *****
 *******
*********

16. How do you generate the Fibonacci sequence using a do-while loop in C?

#include <stdio.h>

int main() {
    int n = 10, a = 0, b = 1, count = 0;
    
    do {
        printf("%d ", a);
        int next = a + b;
        a = b;
        b = next;
        count++;
    } while (count < n);
    
    printf("\n");
    return 0;
}

Output:

0 1 1 2 3 5 8 13 21 34

17. How can you print the n-th row of Pascal's triangle in C?

#include <stdio.h>

int binomialCoeff(int n, int k) {
    int res = 1;
    for (int i = 0; i < k; ++i) {
        res *= (n - i);
        res /= (i + 1);
    }
    return res;
}

int main() {
    int n = 5;
    for (int k = 0; k <= n; k++)
        printf("%d ", binomialCoeff(n, k));
    printf("\n");
    return 0;
}

Output:

1 5 10 10 5 1

18. How do you print a right-angled triangle pattern using a while loop in C?

#include <stdio.h>

int main() {
    int n = 4, i = 1;
    while (i <= n) {
        int j = 1;
        while (j <= i) {
            printf("#");
            j++;
        }
        printf("\n");
        i++;
    }
    return 0;
}

Output:

#
##
###
####

19. How do you print a number pattern using nested for loops in C?

#include <stdio.h>

int main() {
    int n = 4, num = 1;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("%d ", num++);
        }
        printf("\n");
    }
    return 0;
}

Output:

1
2 3
4 5 6
7 8 9 10

Key Takeaways

What You've Mastered

  1. Basics: Variables, loops, functions, arrays, and pointers—the building blocks of C
  2. Memory Management: Understanding malloc() vs calloc() for dynamic memory allocation
  3. Intermediate Challenges: Debugging, optimization, and file handling techniques
  4. Advanced Concepts: Memory management, complex data structures, and performance optimizations
  5. Interview Preparation: Real coding interview questions and answers

Conclusion

Learning C language interview questions and answers is essential for anyone pursuing a career in software development. C remains foundational in computer science due to its versatility and efficient use in system-level programming, embedded systems, and application development.

Whether you're preparing for C language interview questions for freshers or brushing up on advanced concepts for experienced positions, practicing these coding challenges will help build a solid understanding.

C programming is not just another programming language—it is the bedrock of every programmer's journey. Honing your skills in C Programming Coding Questions and Answers helps you think logically, write efficient code, and solve complex problems with confidence.

Advice for Learners

  1. Start with the basics and don't rush; strong fundamentals make advanced topics easier
  2. Practice consistently using coding questions to strengthen problem-solving and debugging skills
  3. Explore advanced concepts gradually, like memory management and optimization, to stand out in interviews

Invest the effort today, and C will pay dividends throughout your software development career.


Frequently Asked Questions

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

For freshers, interview questions tend to be basic in nature, covering data types, loops, arrays, and functions. Common questions include:

2. How do I prepare for C programming coding interviews?

To prepare effectively:

3. What are some advanced C programming interview questions?

Advanced questions include:

4. What is the importance of understanding pointers in C?

Pointers are crucial because they:

5. How do I solve C programming questions for interviews effectively?

Effective problem-solving approach:

  1. Divide the problem into smaller, manageable parts
  2. Write pseudocode first
  3. Check for edge cases
  4. Test solutions thoroughly
  5. Practice various problem types to improve skills

6. What are the key differences between malloc() and calloc()?

malloc():

calloc():

Understanding these differences helps you choose the right function and plan memory usage efficiently.

7. How can I practice C coding questions for interviews?

Practice resources:


Source: NxtWave - CCBP (Continuous Coding Building Practice)

Contact Information: