Nested Loop: confused.

Im just confused on how does a nested loop works, i mean how to read such one



for(int i = 0; i < 10; ++i ){
cout << i;
for(int i = 0; i < 10; ++i){
cout << i*j;
}
cout << '\n';
}

I just want to know the sequence that the compiler will going to execute this, what would be the first one.
could somebody elaborate this for me? i would be very much thankful. plss.

Just print out the counters for each loop and you would be able to see the sequence:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main()
{
    for( int outer = 0 ; outer < 3 ; ++outer )
    {
        std::cout << "outer: " << outer << '\n' ;

        for( int inner = 0 ; inner < 5 ; ++inner )
        {
            std::cout << "    inner: " << inner <<  " (outer:" << outer << ")\n" ;
        }

        std::cout << '\n';
    }
}


http://ideone.com/xSvusH
Make a test program and run it and you will see the result which will help you to understand the code.
@Badz: To add to what JLB and vlad said - the code you posted won't work properly, because you're using the same variable as a counter in both loops. The way the inner loop modifies that counter will screw up the outer loop.

If you look at what JLB posted, you'll notice he used different variables for the counters in each loop.
int i = 0; i < 10

Checks these, sees that the condition (i<0) is true, then begins the nested (second) loop and runs through every iteration of it, then executes the addition (i++) of the second loop, then runs through every iteration of the second loop again (which now has a fresh i=0 initialization) and so on until it has run through loop 2 as many times as is required by loop 1.

Consider loop 1 as "paused" just before the addition (i++) section while it executes loop 2.

Was confusing for me too at first.
thank you so much sir/s ... now i get it.. thanks so much
Topic archived. No new replies allowed.