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

Discussion

Predict the output of below code:

#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,5,15
  • B.3, 2, 15
  • C.1,2,5
  • D.12,15,1

Answer: B

Correct answer: 3, 2, 15

Starting from a = {5, 1, 15, 20, 25}:

  1. i = ++a[1]; - pre-increment, so a[1] becomes 2 and i = 2.
  2. j = a[1]++; - post-increment, so 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 becomes 3.

Printed: 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.