13 Apr 2017

Top 10 C interview questions and answers

#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.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
//Sorting without using temporary variables
#include
#include
int main(){
 int a,b;
 printf("Before swapping:\n");
 printf("Enter value of a: ");
 scanf("%d",&a);
 printf("Enter value of b: ");
 scanf("%d",&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);
 getch();
}

Follow up questions:

[learn_more caption= “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. [/learn_more]
[learn_more caption= “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.  [/learn_more]

#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
?
1
2
3
4
5
A B C D E D C B A
  A B C D C B A
    A B C B A
      A B A
        A
And here is the code.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
//Printing pattern
#include
#include
int main(){
 int n,i,j;
 printf("Enter no of lines: ");
 scanf("%d",&n);
 for(i=0;i<n;i++){
 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);
  }
 printf("\n");
 }
 getch();
}

Follow up questions:

[learn_more caption=”1. What happens if we use %d instead of %c?”] Try it out yourself.[/learn_more]
[learn_more caption=”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.[/learn_more]

#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:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
#include
#include
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 : ");
 scanf("%d",&a);
 r=fibonacci(a);
 printf("The number at position %d is %d",a,r);
 getch();
 return 0;
}

Follow up questions:

[learn_more caption=”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.[/learn_more]
[learn_more caption=”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.[/learn_more]

#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.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include
#include
void checkArmstrong(int temp){
 int sum=0,remainder,num=temp,noOfDigits=0;
 while(temp != 0){ //counts no of digits
 noOfDigits++;
 temp=temp/10;
 }
 temp=num;
 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);
 else
 printf("%d is not an armstrong number.",num);
}
 
int main(){
 int n;
 printf("Enter a number: ");
 scanf("%d",&n);
 checkArmstrong(n);
 getch();
 return 0;
}

Follow up Questions:

[learn_more caption=”1. Is 0 an Armstrong number?”] No O^1=1 and not 0 that’s why.[/learn_more]
[learn_more caption=”2. How many 2 digit numbers are Armstrong numbers?”] 0[/learn_more]
[learn_more caption=”3. Why aren’t there any follow up question on the program?”] I couldn’t think of any that’s why ;-)[/learn_more]

#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:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include
#include
#include
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
 c[i++]=a[i];
 while(j<strlen(b)) //adds the second string to c
 c[i++]=b[j++];
 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: ");
 gets(a);
 printf("Enter the second string: ");
 gets(b);
 concatenate(a,b);
 getch();
 return 0;
}

Follow up Questions:

[learn_more caption=”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.[/learn_more]
[learn_more caption=”2. What if we don’t use \ at the end of the string?”] It will show junk values after the string.[/learn_more]

#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:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include
#include
int main()
{
 int arr[20], n, i, j, pos, temp;
 printf("Enter number of elements (max 20): ");
 scanf("%d", &n);
 for(i=0;i<n;i++){
 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
 pos=i;
 for (j=i+1;j<n;j++ ){  if (*(arr+pos)> *(arr+j)) //checks if arr[pos] is greater than arr[j]
 pos=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");
 for(i=0;i<n;i++)
 printf("%d ", *(arr+i));
 getch();
 return 0;
}

Follow up Questions:

[learn_more caption=”1. What is the bubble sort technique?”] To find about bubble sort check out the post [/learn_more]
[learn_more caption=”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.[/learn_more]

#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.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include
#include
typedef struct{ //structure of emp
 char name[30];
 int age;
 float salary;
}emp;
int main(){
 int n,i;
 emp *employee;
 printf("Enter no of employees: ");
 scanf("%d",&n);
 employee=(emp*)malloc(n*sizeof(emp)); //dynamic memory allocation using malloc()
 for(i=0;i<n;i++){
 printf("\n\nEnter details of employee %d\n",i+1);
 printf("Enter name: ");
 scanf("%s",employee[i].name);
 printf("Enter age: ");
 scanf("%d",&employee[i].age);
 printf("Enter salary: ");
 scanf("%f",&employee[i].salary);
 }
 printf("\nPrinting details of all the employees:\n");
 for(i=0;i<n;i++){
 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);
 }
 getch();
 return 0;
}

Follow up Questions:

[learn_more caption=”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);[/learn_more]
[learn_more caption=”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);[/learn_more]
[learn_more caption=”3. Why using a linked list to do this program be a better option?”] Then we can add and delete any employee details easily.[/learn_more]

#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:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include
#include
void towers(int n,char frompeg,char topeg,char auxpeg){
 // If only 1 disk, make the move and return
 if(n==1){
 printf("\nMove disk 1 from peg %c to peg %c",frompeg,topeg);
 return;
 }
 // Move top n-1 disks from A to B, using C as auxiliary
 towers(n-1,frompeg,auxpeg,topeg);
 // 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
 towers(n-1,auxpeg,topeg,frompeg);
}
int main(){
 int n;
 printf("Enter the number of disks : ");
 scanf("%d",&n);
 printf("The Tower of Hanoi involves the moves :\n\n");
 towers(n,'A','C','B');
 getch();
 return 0;
}

Follow up Question:

[learn_more caption=”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.[/learn_more]

#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:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include
#include
#include
 
int main(int argc,char *argv[])
{
int sum=0,i;
//Compare if proper number of arguments have been entered
if(argc<3)
{
printf("Insufficient number of arguments...\n");
getch();
return 0;
}
 
//Add all the numbers entered using atoi function
for(i=1;i<argc;i++)
{
sum+=atoi(argv[i]);
}
 
//print the sum
printf("Ans=%d",sum);
getch();
}

Follow up Questions:

[learn_more caption=”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.[/learn_more]
[learn_more caption=”2. What if i run it in the usual way?”] It will print “Insufficient number of arguments” because no arguments were passed.[/learn_more]

#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:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
#include
#include
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
{
fscanf(fp,"%c",&ch);
printf("%c",ch);
}//end while
getch();
return 0;
}//end main

Follow up Questions:

[learn_more caption=”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.

No comments:

Post a Comment

commnet here