C Quiz – 104 | Question 3

What’s going to happen when we compile and run the following C program?

filter_none

edit
close

play_arrow

link
brightness_4
code

#include "stdio.h"
  
int main()
{
  int i = 1, j;
  for ( ; ; )
  
    if (i)
        j = --i;
    if (j < 10)
       printf("GeeksQuiz", j++);
    else
       break;
  }
  return 0;
}

chevron_right


(A) Compile Error.
(B) No compile error but it will run into infinite loop printing GeeksQuiz.
(C) No compile error and it’ll print GeeksQuiz 10 times.
(D) No compile error but it’ll print GeeksQuiz 9 times.


Answer: (C)

Explanation: Basically, even though the for loop doesn’t 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 existing the loop if j becomes 10. Please note that j is getting incremented in printf even though there’s no format specifier in format string. That’s why GeeksQuiz would be printed for j=0 to j=9 i.e. a total of 10 times.

Quiz of this Question



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.