C Programming Interview Questions
C Programming Interview Questions
Interview Questions
C Programming Interview Questions
Powered by
Index
1. Write a C program to swap two variables without using a temporary variable 3
2. What is the 8 queens problem. Write a C program to solve it 5
3. Write a C program to print a square matrix helically 7
4. Write a C program to reverse a string 8 8
5. Write a C program to reverse the words in a sentence in place 11
6. Write a C program generate permutations 14
7. Write a C program for calculating the factorial of a number 16
8. Write a C program to calculate pow(x,n) 17
9. Write a C program which does wildcard pattern matching algorithm 18
10. How do you calculate the maximum subarray of a list of numbers 19
Q. Write a C program to swap two variables without using a
temporary variable?
Soln: This question is asked almost always in every interview.
The best way to swap two variables is to use a temporary variable.
int a,b,t;
t = a;
a = b;
b = t;
There is no way better than this as you will find out soon. There are a few slick expressions that do swap
variables without using temporary storage. But they come with their own set of problems.
Method1 (The XOR trick)
a ^= b ^= a ^= b;
Although the code above works fine for most of the cases, it tries to modify variable 'a' two times between
sequence points, so the behavior is undefined. What this means is it wont work in all the cases. This will
also not work for floating-point values. Also, think of a scenario where you have written your code like this
swap(int *a, int *b)
{
*a ^= *b ^= *a ^= *b;
}
Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess
what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting
the variable to zero (ideally it should have swapped the variable with itself). This scenario is quite possible
in sorting algorithms which sometimes try to swap a variable with itself (maybe due to some small, but not
so fatal coding error). One solution to this problem is to check if the numbers to be swapped are already
equal to each other.
swap(int *a, int *b)
{
if(*a!=*b)
{
*a ^= *b ^= *a ^= *b;
}
}
Method 2
This method is also quite popular
a=a+b;
b=a-b;
a=a-b;
But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this might
end up giving you wrong results.
One can also swap two variables using a macro. However, it would be required to pass the type of the
variable to the macro. Also, there is an interesting problem using macros. Suppose you have a swap macro
which looks something like this
#define swap(type,a,b) type temp;temp=a;a=b;b=temp;
Now, think what happens if you pass in something like this
swap(int,temp,a) //You have a variable called "temp" (which is quite possible).
This is how it gets replaced by the macro
int temp;
temp=temp;
temp=b;
b=temp;
Which means it sets the value of "b" to both the variables!. It never swapped them! Scary, isn't it?
So the moral of the story is, dont try to be smart when writing code to swap variables. Use a temporary
variable. Its not only fool proof, but also easier to understand and maintain.
Q. What is the 8 queens problem? Write a C program to solve it?
Soln: The 8 queens problem is a classic problem using the chess board. This problem is to place 8
queens on the chess board so that they do not attack each other horizontally, vertically or
diagonally. It turns out that there are 12 essentially distinct solutions to this problem.
Suppose we have an array t[8] which keeps track of which column is occupied in which row of the
chess board. That is, if t[0]==5, then it means that the queen has been placed in the fifth column of
the first row. We need to couple the backtracking algorithm with a procedure that checks whether
the tuple is completable or not, i.e. to check that the next placed queen 'i' is not menaced by any of
the already placed 'j' (j < i):
Two queens are in the same column if t[i]=t[j]
Two queens are in the same major diagonal if (t[i]-t[j])=(i-j)
two queens are in the same minor diagonal if (t[j]-t[i])=(i-j)
Here is some working C code to solve this problem using backtracking
#include<stdio.h>
static int t[10]={-1};
void queens(int i);
int empty(int i);
void print_solution();
int main()
{
queens(1);
print_solution();
return(0);
}
void queens(int i)
{
for(t[i]=1;t[i]<=8;t[i]++)
{
if(empty(i))
{
if(i==8)
{
print_solution();
/* If this exit is commented, it will show ALL possible combinations */
exit(0);
}
else
{
// Recurse!
queens(i+1);
}
}// if
}// for
}
int empty(int i)
{
int j;
j=1;
while(t[i]!=t[j] && abs(t[i]-t[j])!=(i-j) &&j<8)j++;
return((i==j)?1:0);
}
void print_solution()
{
int i;
for(i=1;i<=8;i++)printf("\nt[%d] = [%d]",i,t[i]);
}
And here is one of the possible solutions
t[1] = [1] // This means the first square of the first row.
t[2] = [5] // This means the fifth square of the second row.
t[3] = [8] ..
t[4] = [6] ..
t[5] = [3] ..
t[6] = [7] ..
t[7] = [2] ..
t[8] = [4] // This means the fourth square of the last row.
Q. Write a C program to print a square matrix helically?
Soln: Here is a C program to print a matrix helically. Printing a matrix helically means printing it in
this spiral fashion
>-----------+
|
+---->--+ |
| | |
| | |
| <---+ |
| |
+-----------+
This is a simple program to print a matrix helically.
#include<stdio.h>
/* HELICAL MATRIX */
int main()
{
int arr[][4] = { {1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13, 14, 15, 16}
};
int i, j, k,middle,size;
printf("\n\n");
size = 4;
for(i=size-1, j=0; i>0; i--, j++)
{
for(k=j; k<i; k++) printf("%d ", arr[j][k]);
for(k=j; k<i; k++) printf("%d ", arr[k][i]);
for(k=i; k>j; k--) printf("%d ", arr[i][k]);
for(k=i; k>j; k--) printf("%d ", arr[k][j]);
}
middle = (size-1)/2;
if (size % 2 == 1) printf("%d", arr[middle][middle]);
printf("\n\n");
return 1;
}
Q. Write a C program to reverse the words in a sentence in
place?
Soln: That is, given a sentence like this - I am a good boy - In place reverse would be boy good a am I
Method1
First reverse the whole string and then individually reverse the words
I am a good boy
<------------->
yob doog a ma I
<-> <--> <-> <-> <->
boy good a am I
Here is some C code to do the same ....
/*
Algorithm..
1. Reverse whole sentence first.
2. Reverse each word individually.
All the reversing happens in-place.
*/
#include <stdio.h>
void rev (char *l, char *r);
int main(int argc, char *argv[])
{
char buf[] = "the world will go on forever";
char *end, *x, *y;
// Reverse the whole sentence first..
for(end=buf; *end; end++);
rev(buf,end-1);
// Now swap each word within sentence...
x = buf-1;
y = buf;
while(x++ < end)
{
if(*x == '\0' || *x == ' ')
{
rev(y,x-1);
y = x+1;
}
}
// Now print the final string....
printf("%s\n",buf);
return(0);
}
// Function to reverse a string in place...
void rev(char *l,char *r)
{
char t;
while(l<r)
{
t = *l;
*l++ = *r;
*r-- = t;
}
}
Method2
Another way to do it is, allocate as much memory as the input for the final output. Start from the
right of the string and copy the words one by one to the output.
Input : I am a good boy
<--
<-------
<---------
<------------
<--------------
Output : boy
: boy good
: boy good a
: boy good a am
: boy good a am I
The only problem to this solution is the extra space required for the output and one has to write this
code really well as we are traversing the string in the reverse direction and there is no null at the
start of the string to know we have reached the start of the string!. One can use the strtok() function
to breakup the string into multiple words and rearrange them in the reverse order later.
Method3
Create a linked list like
+---+ +----------+ +----+ +----------+ +---+ +----------+
| I | -> | <spaces> | -> | am | -> | <spaces> | -> | a | -> | <spaces> | --+
+---+ +----------+ +----+ +----------+ +---+ +----------+ |
|
|
+-------------------------------------------------------------------------+
|
| +------+ +----------+ +-----+ +------+
+---> | good | -> | <spaces> | -> | boy | -> | NULL |
+------+ +----------+ +-----+ +------+
Now its a simple question of reversing the linked list!. There are plenty of algorithms to reverse a
linked list easily. This also keeps track of the number of spaces between the words. Note that the
linked list algorithm, though inefficient, handles multiple spaces between the words really well.
I really dont know what is the use of reversing a string or a sentence like this!, but its still asked. Can
someone tell me a really practical application of this? Please!
Q. Write a C program generate permutations?
Soln: Iterative C program
#include <stdio.h>
#define SIZE 3
int main(char *argv[],int argc)
{
char list[3]={'a','b','c'};
int i,j,k;
for(i=0;i<SIZE;i++)
for(j=0;j<SIZE;j++)
for(k=0;k<SIZE;k++)
if(i!=j && j!=k && i!=k)
printf("%c%c%c\n",list[i],list[j],list[k]);
return(0);
}
Recursive C program
#include <stdio.h>
#define N 5
int main(char *argv[],int argc)
{
char list[5]={'a','b','c','d','e'};
permute(list,0,N);
return(0);
}
void permute(char list[],int k, int m)
{
int i;
char temp;
if(k==m)
{
/* PRINT A FROM k to m! */
for(i=0;i<N;i++){printf("%c",list[i]);}
printf("\n");
}
else
{
for(i=k;i<m;i++)
{
/* swap(a[i],a[m-1]); */
temp=list[i];
list[i]=list[m-1];
list[m-1]=temp;
permute(list,k,m-1);
/* swap(a[m-1],a[i]); */
temp=list[m-1];
list[m-1]=list[i];
list[i]=temp;
}
}
}
Q. Write a C program for calculating the factorial of a number?
Soln: Here is a recursive C program
fact(int n)
{
int fact;
if(n==1)
return(1);
else
fact = n * fact(n-1);
return(fact);
}
Please note that there is no error handling added to this function (to check if n is negative or 0. Or if
n is too large for the system to handle). This is true for most of the answers in this website. Too
much error handling and standard compliance results in a lot of clutter making it difficult to
concentrate on the crux of the solution. You must of course add as much error handling and comply
to the standards of your compiler when you actually write the code to implement these algorithms.
Q. Write a C program to calculate pow(x,n)?
Soln: There are again different methods to do this in C
Brute force C program
int pow(int x, int y)
{
if(y == 1) return x ;
return x * pow(x, y-1) ;
}
Divide and Conquer C program
#include <stdio.h>
int main(int argc, char*argv[])
{
printf("\n[%d]\n",pow(5,4));
}
int pow(int x, int n)
{
if(n==0)return(1);
else if(n%2==0)
{
return(pow(x,n/2)*pow(x,(n/2)));
}
else
{
return(x*pow(x,n/2)*pow(x,(n/2)));
}
}
Also, the code above can be optimized still by calculating pow(z, (n/2)) only one time (instead of twice) and using its
value in the two return() expressions above.
Q. Write a C program which does wildcard pattern matching algorithm?
Soln: Here is an example C program...
#include<stdio.h>
#define TRUE 1
#define FALSE 0
int wildcard(char *string, char *pattern);
int main()
{
char *string = "hereheroherr";
char *pattern = "*hero*";
if(wildcard(string, pattern)==TRUE)
{
printf("\nMatch Found!\n");
}
else
{
printf("\nMatch not found!\n");
}
return(0);
}
int wildcard(char *string, char *pattern)
{
while(*string)
{
switch(*pattern)
{
case '*': do {++pattern;}while(*pattern == '*');
if(!*pattern) return(TRUE);
while(*string){if(wildcard(pattern,string++)==TRUE)return(TRUE);}
return(FALSE);
default : if(*string!=*pattern)return(FALSE); break;
}
++pattern;
++string;
}
while (*pattern == '*') ++pattern;
return !*pattern;
}
Q. How do you calculate the maximum subarray of a list of
numbers?
Soln: This is a very popular question
You are given a large array X of integers (both positive and negative) and you need to find the
maximum sum found in any contiguous subarray of X.
Example X = [11, -12, 15, -3, 8, -9, 1, 8, 10, -2]
Answer is 30.
There are various methods to solve this problem, some are listed below
Brute force
maxSum = 0
for L = 1 to N
{
for R = L to N
{
sum = 0
for i = L to R
{
sum = sum + X[i]
}
maxSum = max(maxSum, sum)
}
}
O(N^3)
Quadratic
Note that sum of [L..R] can be calculated from sum of [L..R-1] very easily.
maxSum = 0
for L = 1 to N
{
sum = 0
for R = L to N
{
sum = sum + X[R]
maxSum = max(maxSum, sum)
}
}
Using divide-and-conquer
O(N log(N))
maxSum(L, R)
{
if L > R then
return 0
if L = R then
return max(0, X[L])
M = (L + R)/2
sum = 0; maxToLeft = 0
for i = M downto L do
{
sum = sum + X[i]
maxToLeft = max(maxToLeft, sum)
}
sum = 0; maxToRight = 0
for i = M to R do
{
sum = sum + X[i]
maxToRight = max(maxToRight, sum)
}
maxCrossing = maxLeft + maxRight
maxInA = maxSum(L,M)
maxInB = maxSum(M+1,R)
return max(maxCrossing, maxInA, maxInB)
}
Here is working C code for all the above cases
#include<stdio.h>
#define N 10
int maxSubSum(int left, int right);
int list[N] = {11, -12, 15, -3, 8, -9, 1, 8, 10, -2};
int main()
{
int i,j,k;
int maxSum, sum;
/*---------------------------------------
* CUBIC - O(n*n*n)
*---------------------------------------*/
maxSum = 0;
for(i=0; i<N; i++)
{
for(j=i; j<N; j++)
{
sum = 0;
for(k=i ; k<j; k++)
{
sum = sum + list[k];
}
maxSum = (maxSum>sum)?maxSum:sum;
}
}
printf("\nmaxSum = [%d]\n", maxSum);
/*-------------------------------------
* Quadratic - O(n*n)
* ------------------------------------ */
maxSum = 0;
for(i=0; i<N; i++)
{
sum=0;
for(j=i; j<N ;j++)
{
sum = sum + list[j];
maxSum = (maxSum>sum)?maxSum:sum;
}
}
printf("\nmaxSum = [%d]\n", maxSum);
/*----------------------------------------
* Divide and Conquer - O(nlog(n))
* -------------------------------------- */
printf("\nmaxSum : [%d]\n", maxSubSum(0,9));
return(0);
}
int maxSubSum(int left, int right)
{
int mid, sum, maxToLeft, maxToRight, maxCrossing, maxInA, maxInB;
int i;
if(left>right){return 0;}
if(left==right){return((0>list[left])?0:list[left]);}
mid = (left + right)/2;
sum=0;
maxToLeft=0;
for(i=mid; i>=left; i--)
{
sum = sum + list[i];
maxToLeft = (maxToLeft>sum)?maxToLeft:sum;
}
sum=0;
maxToRight=0;
for(i=mid+1; i<=right; i++)
{
sum = sum + list[i];
maxToRight = (maxToRight>sum)?maxToRight:sum;
}
maxCrossing = maxToLeft + maxToRight;
maxInA = maxSubSum(left,mid);
maxInB = maxSubSum(mid+1,right);
return(((maxCrossing>maxInA)?maxCrossing:maxInA)>maxInB?((maxCrossing>maxInA)?maxCrossi
ng:maxInA):maxInB);
}
Note that, if the array has all negative numbers, then this code will return 0. This is wrong because it
should return the maximum sum, which is the least negative integer in the array. This happens
because we are setting maxSum to 0 initially. A small change in this code can be used to handle such
cases.
Study on the go; get high quality complete preparation
courses now on your mobile!