Stupid question

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main() {
        int m[3];
        int t;

        for(int i=0;i<3;i++)
            m[i]=i*10;

        for(int j=2;j>0;j--) {
            t=m[j];
            m[j]=m[2-j];
            m[2-j]=t;
        }

        for(int i=0;i<3;i++)
            cout << m[i] << endl;

}


What is the output of this? The j is confusing me. Oh and I'm not using any programs for this.
Last edited on
closed account (S6k9GNh0)
Just curious but why don't you compile it.
When given a problem like this you should trace what the program is doing on apiece of paper (if it's not obvious). This program reverse the m[3] from [0,10,20] to [20,10,0] .

The j is used as a new index for the second for-loop. t is temporary storing the element to be moved. Try it on a piece of paper. Note that while i goes from 0 to 2, the j goes from 2 to 0.
Breaking your sourcecode into logical passages:
1
2
for(int i=0;i<3;i++)
            m[i]=i*10;
m = { 0, 10, 20 }

1
2
3
4
5
for(int j=2;j>0;j--) {
            t=m[j];
            m[j]=m[2-j];
            m[2-j]=t;
        }
j=2
t = m[2] = 20
m[2] = m[2-2] = 0
m[2-2] = t = 20
j=1
t = m[1] = 10
m[1] = m[2-1] = 10
m[2-1] = t = 10


1
2
for(int i=0;i<3;i++)
            cout << m[i] << endl;
m[0] 20
m[1] 10
m[2] 0





Topic archived. No new replies allowed.