Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

#include <stdio.h>
int main()
{
    int i = 5;
    while(i-- >= 0)
        printf("%d,", i);
    i = 5;
    printf("\n");
    while(i-- >= 0)
        printf("%i,", i);
    while(i-- >= 0)
        printf("%d,", i);
    return 0;
}

 

  • A.4, 3, 2, 1, 0, -1
    4, 3, 2, 1, 0, -1
  • B.5, 4, 3, 2, 1, 0
    5, 4, 3, 2, 1, 0
  • C.Error
  • D.5, 4, 3, 2, 1, 0
    5, 4, 3, 2, 1, 0
    5, 4, 3, 2, 1, 0

Answer: A

Correct answer: 4, 3, 2, 1, 0, -1 4, 3, 2, 1, 0, -1

i-- >= 0 tests the old value and then decrements, so the value printed is always one less than the value tested. Starting at 5 that gives 4, 3, 2, 1, 0 and finally -1 - the pass where the test saw 0. The loop then leaves i at -2. After i is reset to 5 the second loop prints the same line. The third loop then starts with i at -2, so its very first test fails and it prints nothing.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.