C Programming - Arrays - Discussion

Discussion Forum : Arrays - Find Output of Program (Q.No. 1)
1.
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;
}
2, 1, 15
1, 2, 5
3, 2, 15
2, 3, 20
Answer: Option
Explanation:

Step 1: int a[5] = {5, 1, 15, 20, 25}; The variable arr is declared as an integer array with a size of 5 and it is initialized to

a[0] = 5, a[1] = 1, a[2] = 15, a[3] = 20, a[4] = 25 .

Step 2: int i, j, m; The variable i,j,m are declared as an integer type.

Step 3: i = ++a[1]; becomes i = ++1; Hence i = 2 and a[1] = 2

Step 4: j = a[1]++; becomes j = 2++; Hence j = 2 and a[1] = 3.

Step 5: m = a[i++]; becomes m = a[2]; Hence m = 15 and i is incremented by 1(i++ means 2++ so i=3)

Step 6: printf("%d, %d, %d", i, j, m); It prints the value of the variables i, j, m

Hence the output of the program is 3, 2, 15

Discussion:
39 comments Page 2 of 4.

Saranya said:   1 decade ago
Sorry i can't understand at step4 of this program explanation

j=2 then there should occur a[2],
but a[1] is came how, and
we get the value a[1]=3;

Please explain.

Mehul said:   1 decade ago
Now i am getting it
see
a[i++] is definately pointing to 15 hence printed

but NOTICE THAT i++ is there hence i=i+1 too keep in your mind .
i=2+1 ==3
hence 3,2,15

Vaibhav said:   7 years ago
M=a[i++] if i is 2 after increment i becomes 3 then a[3]=20.

I can't understand, why (i) not incrementing by 1 in 5th step? Please, someone, help me to get this.
(3)

Bhimeswarrao said:   1 decade ago
At step 4 a[1]=2 so it is directly assigned to j. Then a[1] is incremented by 1.

Because as it is a post increment finaly at step 4 j=2 and a[1]=3.

Mayank said:   8 years ago
Hi,

++a[1] can we written as ++ *(a+1); (associativity right to left)
as *(a+1)=1;
++1; should give error.
But it works why?

OMNARAYAN TIWARI said:   10 years ago
The value of m=a[i++] not clear and its output is also confusing. It seems it's giving the output of j, i, m.

Kaviya.p said:   3 years ago
@Rosh.

The value of j is not incremented the a[1] value is incremented see its because of post incremented.
(1)

Anil said:   1 decade ago
Because i have found i=2 in step 3, and again i++ increment one time in step 5 so, i become =3

Bhavya said:   1 decade ago
please explain 4th line a[1]++ means a[1]=1 since it is post increment we will get as 1

Raghu said:   1 decade ago
I can't undrstand at 5th line in this explanation.

Please any one can explain this.


Post your comments here:

Your comments will be displayed after verification.