nested loops

Im currently taking my first c++ class and i am having a very difficult time understanding nested loops. Could someone walk me thru it? how does the inner loop relate to the outer loop?
for (int i = 1; i<=n; i++)
{
for ( int j = 1; j<= i; j++)
cout << "*";
cout << "\n";
}
closed account (yUq2Nwbp)
first i is initialized with 1,the condition i<=n verifies and then comes second for.....j is initialized with 1 and second for ends when the condition j<=i isn't true...........then it prints "\n" and comes to first for and i gets 2, then verifies whether i<=n conition is true....if true then it passes to second for...........

your program should print something like this

*
**
***
****
.........................
Last edited on
closed account (zb0S216C)
Here's a way to think about them: Gear ratios. For every completion of the inner loop, the outer loop increases/decreases by n. For example:

1
2
3
4
5
for( int iOuter( 0 ); iOuter < 2; iOuter++ )
{
    for( int iInner( 0 ); iInner < 3; iInner++ )
        //...
}


In order for the outer-loop to complete a full loop, the inner-loop must must complete all of it's loops, or break from the loop( whichever comes first ).

Wazzak
closed account (3hM2Nwbp)
A more visual way of how the code executes can be seen by using the Visual Studio debugger. It allows you to step through the code line-by-line so you can actually see what's happening. (That's how I usually taught the control structures to the students that I tutored.)
so does j go back to 1 each time you go thru the outer loop to the inner loop?
closed account (yUq2Nwbp)
lnicole3 of course.......each time it is initialized.....or rather you initialized it each time-> int j=1.
Topic archived. No new replies allowed.