Campbell Ritchie wrote:Outer starts at 0, and is 0 throughout the first loop; it doesn't become 1 until the very end of the loop.
Inner starts at 4 and remains 4 until the end of the loop. You repeat the inner loop (until x becomes 6, when the inner loop is broken).
When you repeat the outer loop, the inner loop starts again from its beginning.
Julian Cadavid wrote:
I'm not understanding the for loop too much I guess.
I thought the loop was supposed to run until the value was no longer true
Tim Harris wrote:
Julian Cadavid wrote:
I'm not understanding the for loop too much I guess.
I thought the loop was supposed to run until the value was no longer true
You have this part correct. Look at the following for loop:
An integer called counter is being created, starting at zero. The system prints out the number of the counter, and then increments the counter. It does this until the loop is no longer true. So this will print:
0
1
2
What I think is confusing you is loops within loops.
Look at the following:
When entering the outer loop, the program then prints the first line of the outer loop. Then it begins to follow through the inner loop, until the inner loop is completed. After the inner loop is completed, the outer loop adds an extra space, goes back around and begins again. If you executed this code, it would look like this:
This statement is in the outer loop: 0
This statement is in the inner loop: 0
This statement is in the inner loop: 1
This statement is in the inner loop: 2
This statement is in the outer loop: 1
This statement is in the inner loop: 0
This statement is in the inner loop: 1
This statement is in the inner loop: 2
This statement is in the outer loop: 2
This statement is in the inner loop: 0
This statement is in the inner loop: 1
This statement is in the inner loop: 2
So, each run of the inner loop is completed before the outer loop begins its next iteration.
I hope this helps!
Julian Cadavid wrote:
why does x go from 0 to 6 then 6 to 12, and then 12 to 18, isn't is adding 6 everytime?
Julian Cadavid wrote:
Also with the y, decrements 2, then 4?
Tim Harris wrote:
Julian Cadavid wrote:
why does x go from 0 to 6 then 6 to 12, and then 12 to 18, isn't is adding 6 everytime?
It is adding six, technically. What it's really doing is assigning x the value of x + 3; but it's doing so in two different places.
Look at lines 10 and 17 of the code and you'll see:
Both of those pieces are happening within the inner loop.
Julian Cadavid wrote:
Also with the y, decrements 2, then 4?
Similar to the x statement, the y statement appears twice as well - however, the second occurrence of it happens in the outer loop, so a total of 4 is taken from y on every outer loop.
Check lines 13 and 19 for those.
Who among you feels worthy enough to be my best friend? Test 1 is to read this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
|