Loops II, 'Whats i?'

The question asks what will print. For (var i =0, i < 5, i = i + 1), print (i) - I think. ( cant go back and copy).

Why would this print 0, and not print 5? If i = i + 1, then i would never be 0, and at 4 would = 5.

Hey there, great question.

A classic for loop has 3 parts in its setup. Let’s look at the following example:

for (var i = 0; i < 3; i = i + 1) {
    print(i);
}

var i = 0, declares a variable and sets its value to 0. This means that when the looping starts, i will start off with a value of 0.

The loop will keep running as long as i < 3 is true. Once it is false, the for loop will stop.

At the end of every loop, i = i + 1 will add 1 to i.

Let’s walk through it:

On the 1st loop: i is 0, i < 3 is true, so the code runs print(i), which prints 0. Then i becomes 1.

On the 2nd loop: i is 1, i < 3 is still true, so the code runs print(i), which prints 1. Then i becomes 2.

On the 3rd loop: i is 2, i < 3 is still true, so the code runs print(i), which prints 2. Then i becomes 3.

On the 4th loop: i is 3, i < 3 is now false, so the for loop stops running.

Hope this helps!
Ben

If i€4 then 1+4=5% and so on and so forth

Thanks Ben!

That helps but I need more. The ‘for’ loop has 4 parts but does the action after the first two, then runs the fourth.

So, for (part a: part b; part c) {action} the sequence of events is “a - b - action - c.”

Then the loop goes “part b - action - part c” for as long as “part b = true.” This because part a is only run once and then ignored, and the reason it prints the initial value of the variable is because the “action” occurs before part c on the first pass through the loop (because part b = true). it stops when part b = false.

Am I making sense?

Joshua

You’ve got the right idea.

Part A runs once before the loop iterates for the 1st time, and sets up the looping variable.

Part B runs at the start of every loop. If part B is true, the for loop runs. If it’s false, the for loop stops.

The code inside the {} then runs.

Part C runs at the end of every loop, and updates the variable set up in Part A.

I think it would help you to practice making a few for loops in the Code Playground, which you can access by tapping the menu button at the top-left corner of the app.

There’s also this video that you might find useful.

A few notes, in the playground, use console.log() instead of print(). print() is a Grasshopper custom function we wrote that we use only in Fundamentals I. It’s just console.log() renamed to be more beginner-friendly, and in Fundamentals II we teach users to transition to console.log()

Also, in the video you’ll see ++ used, for example, i++. This is just a shorter way of writing i = i + 1. This is also taught in Fundamentals II.

Let me know if you have any questions!
Ben