GATE | GATE 2017 MOCK II | Question 13

What will the output of the following C code ?

#include <stdio.h>
int main()
{
   int i=2, j=2;
   while (i+1 ? --i : j++)
      printf("%d",i);
   return 0;
}

(A) 1
(B) 2
(C) 3
(D) 4


Answer: (A)

Explanation: Consider the while loop condition => i + 1 ? –i : j++

In first iteration :



i + 1 = 3 (true)
So ternary operator will return –i i.e. 1, condition part is 1 means true so while condition is true.
Hence printf statement will print 1

In second iteration :
i + 1 =2 (true)
So ternary operator will return –i i.e 0, condition part is 0 means false so while condition is false.
Hence program control will come out of the while loop.


Quiz of this Question



My Personal Notes arrow_drop_up
Article Tags :

Be the First to upvote.


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