nested for loop confused with result

• 07-13-2013, 04:16 AM
sayswho
nested for loop confused with result
Hi,

I have this code:
Code:

```for (int i=0;i<=5;i++)//this are rows  -6 - outer loop will be executed 6 times                 {                         for (int j=0;j<=i;j++) //this are char numbers- inner loop will execute 6 times                         {                                 System.out.print("*");                         }                         System.out.print("\n");                 }```
The output is:

Code:

```* ** *** **** ***** ******```
So here is what I don't understand:
For line 1 outer loop i=0; then goes to inner loop j is initialised to 0 so 0<=0 is true;
then it prints *. And then j is incremented?

Or it prints * then does
Code:

`System.out.print("\n");`
then it goes back to outer loop i is incremented and now i=1; and then j is incremented?
And line 2:
**

i=1;j=1; so 1<=1 true and then it should print *..increment j =2 test the condition 2 is not <=1 and it should exit inner loop? how do I get ** printed?
• 07-13-2013, 10:55 AM
Toll
Re: nested for loop confused with result
Let's go through exactly what happens.

When i is 0, then the inner loop will happen while i is less than or equal to zero, i.e. one step.
When i is 1, then the inner loop will happen while i is less than or equal to one, i.e. two steps. Remember that j is set to 0 at the start of _every_ inner loop, just not the first one.
When i is 2, the inner loop will happen three times (for j==0, j==1 and j==2).
And so on.
• 07-14-2013, 12:26 PM
sayswho
Re: nested for loop confused with result
Thank you:(nod): yes..it just hit me yesterday that because the 2nd loop is inside of the outer loop that means that variables inside of it get destroyed every time the iteration of outer loop is over; re-read info about variable scope