Amanshu Kataria
Amanshu Kataria

Reputation: 3346

Getting unexpected output

Can anyone please help me understand how the output is 3 2 15 for the following code?

I am expecting output as: 2 2 15 because

Please help me if I am wrong.

#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\n",i,j,m);
    return 0;
}

Upvotes: 0

Views: 75

Answers (6)

Ankur
Ankur

Reputation: 3724

a[1]=1;
i=++a[1]; //a[1] is pre-incremented by 1 so i=2;
j=a[1]++; // a[1] is post incremented by 1 so j=2;
m=a[i++]; // i is post incremented by 1  so m =a[2] so m=15
          // as i was post incremented so i=2+1 in next step.

Upvotes: 0

Sunil Bojanapally
Sunil Bojanapally

Reputation: 12658

i=++a[1]; ==> ++a[1] == 2 

i gets the value of pre incremented of array a[1], which is 2

j=a[1]++; ==> a[1]++ == 2

Similarly j becomes 2 but post incremented.

m=a[i++]; ==> a[3] == 15 /* Here i became 3*/

Here first i which is already 2 incremented by 1 becoming 3 which is post incremented in next statement, resulting m gets assigned with a[2] which is 15.

Upvotes: 0

Begah
Begah

Reputation: 128

The second menber of your array is 1. So doing i=++a[1]; translates to i=++1;. this is 2. J is the same thing ( in this case ). Then you take out the second value of your array (15) with "i" which is two, then you add one to "i". Resulting in i=3, j=2 and m=15.

Note : i=++1; is just to visualize what is happening, this shouldn't and can't be used.

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36438

int a[5]={5,1,15,20,25};

Increment a[1] to 2, and set i to that

i=++a[1]; 

Set j to a[1] (2), then increment a[1] to 3

j=a[1]++;

set m to a[i] (a[2], or 15), then increment i to 3

m=a[i++];

Upvotes: 4

Scott Hunter
Scott Hunter

Reputation: 49803

  • a[1] get incremented to 2; i gets assigned this value
  • the value of a[1] (still 2) also gets assigned to j, after which a[1] gets incremented to 3
  • a[2] (15) gets assigned to m; then i gets incremented to 3

Upvotes: 0

Gopi
Gopi

Reputation: 19864

    i=++a[1]; /* a[1] = 1 and you have a pre-increment so */

    i = 2;

    j = a[1]++; /* a[1] = 2  and post-increment so j = 2 */

    j= 2

    m=a[i++]; /* m = a[2] = 15 and `i` is incremented later i = 3 */

    m = 15

    i = 3

So i=3 j = 2 and m = 15

Upvotes: 1

Related Questions