for loop help

CAN SOMEONE PLEASE EXPLAIN THIS CODE, STEP BY STEP FOR ME. I DONT UNDERSTAND HOW ITS PRINTING 6677

#include <iostream>

using namespace std;

int main()
{
const int x = 10;
int y[x] = {7,5,7,6,0,2,0,6,9,2};
int z =10;

for (int i=0; i<z; i+=2) {
z--;
cout<<y[y[i]]<<endl;
}
}
There are two parts to this.

The first is to understand why the loop executes four times, and what is the value of i each time. Consider that first.

Then when you've done that, start to look at the cout statement, and interpret what it means.
I dont understand why the loop executes 4 times. the z-- throws me off completely. can you please explain it to me
i know y[i] = 7700 but I dont understand y[y[i]]= 6677.
I dont understand why the loop executes 4 times.


Then consider this code (try to run it)
1
2
3
4
5
6
7
    int z =10;

    for (int i=0; i<z; i+=2) 
    {
        z--;
        cout << "i = " << i << "    z = " << z << '\n';
    }


When there's something that seems puzzling, often getting more information can help to stabilise your thinking, so instead of a vague sense of mystery, there are solid facts to look at.
i know y[i] = 7700 but
y[i] is meaningless unless you specify the value of i.
But in any case, it won't be 7700, it has to be one of these: {7,5,7,6,0,2,0,6,9,2};
edit: I may have misunderstood your meaning.

One step at a time
consider this:
1
2
3
4
5
    for (int i=0; i<z; i+=2) 
    {
        z--;
        cout << "i - " << i  << "    y[i] = "  << y[i] << '\n';
    }


Now you know the individual, separate values of y[i] you can put that into its original context.

If it helps, look at this:
1
2
3
4
5
6
7
8
    for (int i=0; i<z; i+=2) 
    {
        z--;
        
        int index = y[i];
        cout << "index  = " << index  << "    y[index] = "  << y[index] << '\n';        
        
    }


Last edited on
okay that was a much clearer example on whats going on. i still dont understand why i =0,2,4,6 and not 0,2,4,6,8 since 8 is smaller than 10? same for z
thanks for helping me through this chervil!
OKAY!! thanks man I finally understand it!!!! appreciate your time!
that second example really made me see it clearly!! thanks Chervil
Last edited on
Topic archived. No new replies allowed.