Fresher C Interview Questions

What are storage classes in C?

ClassMeaning
autoDefault for local variables
staticKeeps its value between function calls
externUses a variable defined in another file or place
registerHint to keep the variable in a CPU register

See the full explanation in Scope and Storage Classes.

What is the use of the static keyword in C?

A static local variable is created once and keeps its value between function calls. A static global variable or function is visible only in its own file.

#include <stdio.h>

void count(void) {
    static int n = 0;
    n++;
    printf("%d ", n);
}

int main(void) {
    count(); count(); count();
    printf("\n");
    return 0;
}

Output:

Output of the above program is

1 2 3

A normal local variable would print 1 every time.

What is an enum in C?

#include <stdio.h>

enum Day { MON, TUE, WED };

int main(void) {
    enum Day d = TUE;
    printf("%d\n", d);
    return 0;
}

Output:

Output of the above program is

1

Names make the code easy to read. You can also set values, like enum Level { LOW = 1, HIGH = 10 };. See C enum.

How to reverse a string in C?

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

int main(void) {
    char s[] = "Hello";
    int i = 0, j = strlen(s) - 1;

    while (i < j) {
        char t = s[i];
        s[i] = s[j];
        s[j] = t;
        i++;
        j--;
    }
    printf("%s\n", s);
    return 0;
}

Output:

Output of the above program is

olleH

More ways are in Reverse a String in C.

How to swap two numbers in C?

#include <stdio.h>

int main(void) {
    int a = 10, b = 20, t;

    t = a;  a = b;  b = t;           // with a third variable
    printf("%d %d\n", a, b);

    a = a + b;  b = a - b;  a = a - b;   // without a third variable
    printf("%d %d\n", a, b);
    return 0;
}

Output:

Output of the above program is

20 10
10 20

In a function, send the addresses (swap(&a, &b)) and use pointers. See Call by Value and Reference.

How to check if a number is prime in C?

#include <stdio.h>

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

int main(void) {
    printf("%d\n", isPrime(29));
    printf("%d\n", isPrime(30));
    return 0;
}

Output:

Output of the above program is

1
0

It is enough to check divisors up to the square root of the number, so the loop is fast.

How to find the factorial of a number in C?

#include <stdio.h>

int main(void) {
    int n = 5;
    unsigned long long fact = 1;

    for (int i = 2; i <= n; i++) {
        fact *= i;
    }
    printf("%d! = %llu\n", n, fact);
    return 0;
}

Output:

Output of the above program is

5! = 120

Factorial grows very fast. Even unsigned long long overflows after 20!. The recursive way is in C Recursion.