Common C Programming Interview Questions and Answers
Reverse a String
#include <stdio.h>
#include <string.h>
void reverseString(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";
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
Check if a Number is Prime
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
return true;
int main() {
int num = 29;
if (isPrime(num)) {
printf("%d is a prime number\n", num);
} else {
printf("%d is not a prime number\n", num);
return 0;
Fibonacci Series
#include <stdio.h>
void fibonacci(int n) {
int a = 0, b = 1, next;
for (int i = 1; i <= n; i++) {
printf("%d ", a);
next = a + b;
a = b;
b = next;
}
printf("\n");
int main() {
int n = 10;
fibonacci(n);
return 0;
Find the Largest Element in an Array
#include <stdio.h>
int findLargest(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
return max;
int main() {
int arr[] = {1, 8, 3, 7, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int largest = findLargest(arr, n);
printf("Largest element: %d\n", largest);
return 0;
Generic Bubble Sort
#include <stdio.h>
#include <string.h>
void swap(void *a, void *b, size_t size) {
void *temp = malloc(size);
if (temp == NULL) {
printf("Memory allocation failed\n");
exit(1);
memcpy(temp, a, size);
memcpy(a, b, size);
memcpy(b, temp, size);
free(temp);
void bubbleSort(void *arr, size_t n, size_t size, int (*cmp)(const void *, const void *)) {
for (size_t i = 0; i < n - 1; i++) {
for (size_t j = 0; j < n - i - 1; j++) {
void *a = (char*)arr + j * size;
void *b = (char*)arr + (j + 1) * size;
if (cmp(a, b) > 0) {
swap(a, b, size);
}
int intCompare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
size_t n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n, sizeof(int), intCompare);
printf("Sorted array: ");
for (size_t i = 0; i < n; i++) {
printf("%d ", arr[i]);
printf("\n");
return 0;
Find GCD of Two Numbers
#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 a = 56, b = 98;
printf("GCD of %d and %d is %d\n", a, b, gcd(a, b));
return 0;
Check if a String is Palindrome
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isPalindrome(char *str) {
int l = 0;
int h = strlen(str) - 1;
while (h > l) {
if (str[l++] != str[h--]) {
return false;
}
return true;
int main() {
char str[] = "radar";
if (isPalindrome(str)) {
printf("%s is a palindrome\n", str);
} else {
printf("%s is not a palindrome\n", str);
return 0;