Recap of For Loops
What We’ve Covered So Far
A for loop is a way to make a piece of code repeat a certain number of times.
The header of a for loop has three pieces. These pieces do the following:
1. Create an integer for keeping track of how many times the for loop has executed.
2. Check a condition to see if the for loop should execute again.
3. Add to the integer which keeps track of how many times the for loop has executed. (Sometimes it may even subtract from the integer.)
After the for loop header is done the for loop will execute any code inside its curly brackets.
Remember! If the for loop header starts with i = 0 then the robot will start counting at zero.
This may trip you up and cause you to write code that executes one more time than you want.
Questions and Activities to Try
1. Create a for loop that makes Sparki beep eight times. Click here for help with making Sparki beep.
2. Change the for loop you just made so that it uses the variable i to make Sparki beep a different musical note each time through the for loop.
3. Now change the for loop header so that instead of adding one to i each time through, Sparki subtracts from i each time through the for loop. This should make Sparki’s beeps get lower and lower as you go through the for loop. (If your for loop from above already made Sparki’s beeps get lower and lower then this should flip it so that Sparki’s beeps get higher and higher as it goes through the for loops.)
Phew. You’re almost at the end of these basic coding lessons. You’ve covered a lot of ground since you started. Let’s go over just a couple more tips and tricks before setting you loose to write code on your own.