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 a[5] = {5, 1, 15, 20, 25};
    int i, j, m;
    i = ++a[1];
    j = a[1]++;
    m = a[i++];
    printf("%d, %d, %d", i, j, m);
    return 0;
}

 

  • A.2, 1, 15
  • B.1, 2, 5
  • C.3, 2, 15
  • D.2, 3, 20

Answer: C

Correct answer: 3, 2, 15

Take the three statements in order, starting from a = {5, 1, 15, 20, 25}.

  1. i = ++a[1]; - pre-increment: a[1] becomes 2 and that new value is assigned, so i = 2.
  2. j = a[1]++; - post-increment: j = 2 (the old value), and a[1] becomes 3.
  3. m = a[i++]; - the subscript is the old i, so m = a[2] = 15, and i then becomes 3.

The printed values are therefore 3, 2, 15.

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

Post your comment

Please log in or register to post a comment.