Print Friendly and PDF

If you haven’t opened Turbo C++ for more than a year and the campus placements are not very far away then you are at the correct place. The interviewers have a thing for C programs and there’s a great chance you might be bombarded with them on the interview day. I’ve compiled 10 programs that are very common and has been asked numerous times in the interviews. Most importantly if you practice these programs you get to revise the whole syllabus. I tried to include as many concepts as possible keeping in mind the difficulty level matched the level of the interview questions. If you don’t get any of these questions in the interview feel free to sue this website’s admin.. :mrgreen: Click here to check out 10 java programs for technical interview.

#1: Swap two numbers (without using a temporary variable)

Now there are a number of ways you can do this program but there is one way you can really impress the interviewer which uses this cool technique using bitwise operators.

//Sorting without using temporary variables
int main(){
 int a,b;
 printf("Before swapping:\n");
 printf("Enter value of a: ");
 printf("Enter value of b: ");
 //Sorting using
 a=a^b; //uses xor operator
 b=a^b; //to swap the values
 a=a^b; //of a and b
 printf("After swapping:\n");
 printf("Value of a: %d \nValue of b: %d",a,b);

Follow up questions:

1. What is XOR gate?

Don’t try to give them any other answers because the answer they are looking for is XOR gate outputs 1 when there are odd number of 1s.

2. Show some other ways to do the swapping.

You can add the two numbers and store it in the first number and then subtract the other number from it to swap the value. Or you can multiply and then divide.  

#2: Patterns (one of their favorites)

If the interviewer asks you a pattern and you don’t know how to do that you are screwed big time. Often you might make a very simple mistake which the interviewer was actually looking for. Here we’ll find out how to print this pattern

  A B C D C B A
    A B C B A
      A B A

And here is the code.

//Printing pattern
int main(){
 int n,i,j;
 printf("Enter no of lines: ");
 for(j=0;j<i;j++){ //for printing spaces
 printf(" ");
 for(j=0;j<n-i;j++){ //for printing the left side
  printf("%c ",'A'+j); //the value of j is added to 'A'(ascii value=65)
  for(j=n-i-2;j>=0;j--){ //for printing the right side
    printf("%c ",'A'+j);

Follow up questions:

1. What happens if we use %d instead of %c?

 Try it out yourself.

2. Can't we use ASCII values to print this pattern?

We are indirectly using ASCII values only. If you are still having problems you can visit my post on patterns.

#3: Finding the nth Fibonacci number using recursion

There are two rules in recursion:

i. The function must have a recursive definition or in simple words can be expressed in its own form.

ii. There is a terminating value for which we know the return value of the function.

We have to make a function fibonacci in a recursive form. We’ll make a function fibonacci() and make them follow the above rules:

i. fibonacci(x) = fibonacci(x-1) + fibonacci(x-2) (recursive definition)

ii. if x==0 or x==1 then return 1 (terminating step)

Now we are good to write the code:

int y;
fibonacci(int x){
 if(x==1 || x==0) //terminating step
 return x;
 y=fibonacci(x-1)+fibonacci(x-2); //recursive definition
 return y;
int main(){
 int a,r;
 printf("Enter the position : ");
 printf("The number at position %d is %d",a,r);
 return 0;

Follow up questions:

1. Can we use this function to print the whole Fibonacci series?

 We need to write a for loop from 1 to n and call fibonacci() for each value of i. It’s a bad technique anyway so don’t use it.

2. What if we pass a negative number to the fibonacci() ?

 Try it yourself to find out and rewrite the program to print 0 in that case.

#4: Armstrong number

You have done great so far but don’t try to do the whole tutorial all at once. Take some rest and come back later but if u want a challenge then continue. Now what is an Armstrong number? If a number has n digits and the sum of the nth power of its digits is the number itself then the number is an Armstrong number. Surely you got confused. Here are some examples to help you out.

5^1=5 (so its an Armstrong number)

1^4+6^4+3^4+4^4=1634 (so its another Armstrong number)

Don’t scratch your head if you can’t do it yourself. The code is given below. Feel free to peek.

void checkArmstrong(int temp){
 int sum=0,remainder,num=temp,noOfDigits=0;
 while(temp != 0){ //counts no of digits
 while(temp != 0){ //calculates the sum of the digits
 remainder = temp%10; //to the power noOfDigits
 sum = sum + pow(remainder,noOfDigits);
 temp = temp/10;
 if (num == sum) //checks if the number is an armstrong no. or not
 printf("%d is an armstrong number.",num);
 printf("%d is not an armstrong number.",num);

int main(){
 int n;
 printf("Enter a number: ");
 return 0;

Follow up Questions:

1. Is 0 an Armstrong number?

 No O^1=1 and not 0 that’s why.

2. How many 2 digit numbers are Armstrong numbers?


3. Why aren't there any follow up question on the program?

 I couldn’t think of any that’s why ;-)

#5: Concatenate two strings without using strcat()

We are so used to using strcat() when it comes to concatenate two strings but how can we do that without using strcat()? To answer that you have to know what is string in C and how it is printed. Strings in C are represented by character arrays. The end of the string is marked by a special character known as the null character(). So to concatenate two strings you just have to add the characters of the second character array after the first and place a null character at the end.

The code is as follows:

void concatenate(char a[],char b[]){
 char c[strlen(a)+strlen(b)]; //size of c is sum of a and b
 int i=0,j=0;
 while(i<strlen(a)) //adds the first string to c
 while(j<strlen(b)) //adds the second string to c
 c[i]='\0'; //finally add the null character
 printf("After concatenation:\n");
 printf("Value = %s",c);
int main(){
 char a[30], b[30];
 printf("Enter the first string: ");
 printf("Enter the second string: ");
 return 0;

Follow up Questions:

1. What if we use scanf instead of gets?

 scanf can take in only one word whereas gets can take many words. Use scanf instead of gets to find the difference.

2. What if we don't use at the end of the string?

 It will show junk values after the string.

#6: Sort elements of an array using pointers (selection sort technique)

Sorting is a one of the most favorite topic asked during the interviews. It is usually accompanied by something or the other like here sorting is done indirectly using pointers. There are many sorting techniques but usually bubble sort or selection sort is asked. Here we’ll using the selection sort technique to sort in ascending order. Sorting the elements of the array using pointers makes the program a bit challenging. If there is an integer array arr[], arr is a pointer which stores the address of the first element of arr[]. *arr can be used to refer to the value stored at that location. To access the next element we can use *(arr+1). Using this knowledge you can start writing the program. The code is as follows:

int main()
 int arr[20], n, i, j, pos, temp;
 printf("Enter number of elements (max 20): ");
 scanf("%d", &n);
 printf("Enter no %d: ", i+1);
 scanf("%d",(arr+i)); //(arr+i) is the pointer to the individual elements of the array
 for (i=0;i<(n-1);i++){ //selection sorting is done
 for (j=i+1;j<n;j++ ){  if (*(arr+pos)> *(arr+j)) //checks if arr[pos] is greater than arr[j]
 if ( pos!=i ){ //if value of pos changes the swapping is done
 temp= *(arr+i);
 *(arr+i)= *(arr+pos);
 *(arr+pos)= temp;
 printf("Sorted list in ascending order:\n");
 printf("%d ", *(arr+i));
 return 0;

Follow up Questions:

1. What is the bubble sort technique?

 To find about bubble sort check out the post 

2. What are the other sorting techniques that are asked during the interviews?

 It’s unlikely that they will ask you to write the program but logic of heap sort, merge sort, bucket sort, quick sort and radix sort can be asked.

#7: Enter and print details of n employees using structures and dynamic memory allocation

This program is used to show the most basic use of structures. The structure is made of a character array name[], integer age and float salary. We’ll make an array of the structure for the employees. We’ll also use dynamic memory allocation using malloc. You can also use a linked list to the same which is a better option. Let’s check the code.

typedef struct{ //structure of emp
 char name[30];
 int age;
 float salary;
int main(){
 int n,i;
 emp *employee;
 printf("Enter no of employees: ");
 employee=(emp*)malloc(n*sizeof(emp)); //dynamic memory allocation using malloc()
 printf("\n\nEnter details of employee %d\n",i+1);
 printf("Enter name: ");
 printf("Enter age: ");
 printf("Enter salary: ");
 printf("\nPrinting details of all the employees:\n");
 printf("\n\nDetails of employee %d\n",i+1);
 printf("\nName: %s",employee[i].name);
 printf("\nAge: %d",employee[i].age);
 printf("\nSalary: %.2f",employee[i].salary);
 return 0;

Follow up Questions:

1. What is malloc?

 malloc() is a built-in standard library function for dynamic memory allocation. It allocates a block of size bytes from the free data area (heap). It allows a program to allocate an exact amount of memory explicitly, as and when needed.

Syntax: void *malloc(size_t size);

2. What are the other functions used in dynamic memory allocation/de-allocation?

 calloc, free and realloc. calloc() does the same thing as malloc but has a different syntax. free() is used for de-allocating a memory block previously allocated by malloc() or calloc(). realloc() is used to adjust the amount of memory allocated earlier.

syntax: void *calloc(size_t nitems, size_t size);

void free(void *block);

void *realloc(void *block, size_t size);

3. Why using a linked list to do this program be a better option?

 Then we can add and delete any employee details easily.

#8: Tower of Hanoi using recursion

Now take a small break because you deserve it. But if you have the interview tomorrow, gulp a glass of health drink and continue. The Tower of Hanoi is a mathematical game consisting of three rods A, B and C and a number of disks of different sizes which can slide onto any rod. The objective of the game is to move the entire stack from A to C using B as an auxiliary. There are few rules- Only one disk can be moved at a time and no disk can be placed on top of a smaller disk.

Recursive solution:

  1. move n−1 discs from A to B. This leaves disc n alone on peg A
  2. move disc n from A to C
  3. move n−1 discs from B to C so they sit on disc n

Here’s the code:

void towers(int n,char frompeg,char topeg,char auxpeg){
 // If only 1 disk, make the move and return
 printf("\nMove disk 1 from peg %c to peg %c",frompeg,topeg);
 // Move top n-1 disks from A to B, using C as auxiliary
 // Move remaining disks from A to C
 printf("\nMove disk %d from peg %c to peg %c",n,frompeg,topeg);
 // Move n-1 disks from B to C using A as auxiliary
int main(){
 int n;
 printf("Enter the number of disks : ");
 printf("The Tower of Hanoi involves the moves :\n\n");
 return 0;

Follow up Question:

1. Can we write of Hanoi without using recursion?

 Yes we can write it without using recursion but then we have to alternate between the smallest and the next-smallest disks. Follow these steps:

For an even number of disks:

  • make the legal move between pegs A and B
  • make the legal move between pegs A and C
  • make the legal move between pegs B and C
  • repeat until complete

For an odd number of disks:

  • make the legal move between pegs A and C
  • make the legal move between pegs A and B
  • make the legal move between pegs B and C
  • repeat until complete

In each case, a total of 2n-1 moves are made.

#9: Add numbers using Command line arguments

Questions on command line arguments are very often asked in the interviews. This program will explain most of the details about command line arguments. The main() must have two parameters- int argc and char *argv[]. argc is the argument count and argv[] will store the arguments passed by the user. argv[0] is the name of the program. In this program we’ll have to add all the arguments passed starting from the argv[1] to argv[argc].

The code is given below:


int main(int argc,char *argv[])
int sum=0,i;
//Compare if proper number of arguments have been entered
printf("Insufficient number of arguments...\n");
return 0;

//Add all the numbers entered using atoi function

//print the sum

Follow up Questions:

1. How can i run this program?

 First you have to compile the program. Then you have to run the program in command prompt and also provide the command line arguments properly to get the answer.

2. What if i run it in the usual way?

 It will print “Insufficient number of arguments” because no arguments were passed.

#10: Print its own source code using File

This is a very interesting program. We’ll print the source file (programName.c) without taking any input from the user. We’ll be using command line arguments. As we know the first argument is the file name we’ll be using this concept to make programName.c by adding “.c” to the file name. Then we will open the file in read mode and print the characters from the file. The source code is given below:

int main(int argc,char *argv[])
FILE *fp;
argv[0]=strcat(argv[0],".c"); //to add .c to the name of the file
fp=fopen(argv[0],"r"); //opens the file in read mode
char ch;
while(!feof(fp)) //till it reaches the end of file
}//end while
return 0;
}//end main

Follow up Questions:

1. What are the modes used in fopen?

 There are 6 modes:

“r” Open a file for reading. The file must exist.
“w” Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.
“a” Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist.
“r+” Open a file for update both reading and writing. The file must exist.
“w+” Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.
“a+” Open a file for reading and appending.

2. What is feof?

 It checks whether the End-of-File indicator associated with stream is set, returning a value different from zero if it is. This indicator is generally set by a previous operation on the stream that reached the End-of-File. 

We have reached the end of this long tutorial. Hopefully you enjoyed reading this and good luck for your campus placements. If you have any doubts please use the comments.  Thank you and visit our academic section for more tutorials. You can also find 10 Java concepts for interviews by clicking on this link.

has written 12 posts

Hi, I'm a student and I'm programming in C/CPP for the the past 8years. I also have knowledge on Java, Html, JavaScript and Php. Also I'm a failed stand-up comic and will be testing my skills in this blog...:D

Comments Feed


27 Responses

Comment Now

  1. arnab das says:

    nice work some pointers on pointers ,memory management issues are very helpful for campus-sing enthusiasts for e litmus ,netscape, tally’s c rounds.well done,keep posting.

  2. tharaka prasad says:

    nice work.well done.

  3. Hi
    Can you help me in the below situation
    I have an array a={1,2,3,4,-1,-1,-1}. Am considering this -1 as junk values. I have to remove these junk values and return an array containing b={1,2,3,4}.
    I have tried different ways with no help.
    Please share your ideas so that it will help me.

    • 1. Find out how many non junk values are present.
      2. Then use malloc to generate an array of appropriate size
      3. Copy the non junk values into the array

  4. You have made a good job. We need more advance… so keep it up……

  5. hi arnab…..can u tell me how to print anything on output screen using pointers and without using any i/o function??
    this was asked to me in an interview…..a got a hint from someone that u shold put the adress of the output in pointer and write that text in that memory….something like that…can u help??

  6. thank u……
    good job

  7. I am fresher , looking for career in Embed domain , I am doing well in C pls send me some interview questions to my mail id …

    thank you.

  8. Super but program is very so simple,,,,,,

  9. debanjali saha says:

    thankss a lott….

  10. great job arnab…

  11. Arpan Dixt says:

    Good job arnab..@ i have 1 suggestion ..can u please put some quetions related to data structures using c,like Array or linked list implementation.. that quetions which generally asked in interview from data structures. Thanx :)

  12. In the #7 program you should use -> operator instead of . operator since its a pointer….

  13. nice job arnab,thank u very much,,its very usefull for freshers

  14. Its very useful for me to attend the interview

  15. Mubin Kazi says:

    Thank You buddy… By this i got a better idea where to start from…

  16. thank you sir..

  17. what about 1 to 9 is these numbers are Armstrong or not

  18. Shyam........... says:

    thanks…. good job…

  19. These are really very imp questions to practice before interview. In my Teradata interview I got 2 from these.
    1st is the Swapping program.
    2nd is the Armstrong program.

Leave a Reply


Trackback URL

  1. 10 Java Concepts you must know before appearing for technical interview - Intechgrity - […] With the 10 concepts in mind and the ways to answer the question, you are armed to crack a…