Please Turn On Java Script To Access This Site.

C Institute | Questions


Previous Topic : switch statement - 2Next Topic : for loop - 2

This section focuses on C interview questions, tricky questions, and puzzles, and viva questions based on “for loop statement”. One shall practice these questions and puzzles to improve their C programming skills needed for various interviews (campus interviews, walk-in interviews, viva exams and company interviews), placements, entrance exams and other competitive exams. These programming questions can be attempted by anyone focusing on learning C Programming language. They can be a beginner, fresher, engineering graduate, engineering student, bca student, mca student, mcs students or an experienced IT professional. It will improve their understanding of C Language. Here is a listing of C questions and puzzles on “for loop statement” along with answers and/or explanations.

Q1: How many times will New India be printed in the following program?
#include <stdio.h> 
int main()
{   int a = 512<<1;
    for (; a; a>>= 1)
        printf("New India");
    return 0;
}

a)  10
b)  11
c)  Ininite
d)  Syntax Error
Correct Answer : b
Explanation : The initial value of a is 1024, because 512<<1 results in 1024. In for loop, mentioning initialization is optional. >>= is a short hand assignment operator. It shifts the binary representation of the value by 1 to the right and assigns the resulting value to the same variable. The for loop is executed until value of variable a does not drop to 0.


Q2: #include<stdio.h>
int main()
{  int n;
   for (n = 9; n!=0; n--)
     printf("n = %d", n--);
   return 0;
}
a)  9 8 7 6 5 4 3 2 1
b)  9 7 5 3 1
c)  Infininte
d)  9 8 7 6 5 4 3 2 1 0
Correct Answer : c


Q3: What’s going to happen when we compile and run the following C program?
#include "stdio.h"
 
int main()
{
  int i = 1, j;
  for ( ; ; )
  { 
    if (i)
        j = --i;
    if (j < 10)
       printf("Tarun", j++);
    else
       break;
  }
  return 0;
}
a)  Syntax Error
b)  Tarun will be printed one time.
c)  Tarun will be printed nine time.
d)  Tarun will be printed ten time.
Correct Answer : d
Explanation : The for loop does not have any of three expressions in parenthesis, the initialization, control and increment has been done in the body of the loop. So j would be initialized to 0 via first if. This if itself would be executed only once due to --i. Next if and else blocks are being used to check the value of j and exiting the loop if j becomes 10. Notice that j is getting incremented in printf even though there is no format specifier in format string. So Tarun would be printed for j=0 to j=9, total 10 times.


Previous Topic : switch statement - 2Next Topic : for loop - 2