Loops
Learn about loops and how to use them

What are Loops?

Loops let us repeat parts of our code over again. We can have them repeat for a certain number of times or until something else happens.

We will start with while loops. While loops work similar to if statements (checkout this page if you want to learn more about if statements), but instead of doing the code once, it will keep looping until the condition is false.

So we can uses these with variables to create test programs:

This will keep adding 1 to A while it is less than 8, once it is not less than 8 it will exit out of the loop. Note that it only checks after it has finished all of the code in the loop.

So even though this code adds 10 to A (which would cause A to be greater than 8) it will not stop because it then subtracts 9 from A before it checks to see if it is less than 8. So the order would be this:

  1. Check if A is less than 8
  2.   Add 10 to A  (A is 10)
  3.   Subtract 9 from A (A is 1)
  4. Check if A is less than 8
  5.   Add 10 to A  (A is 11)
  6.   Subtract 9 from A (A is 2)
  7. Check if A is less than 8
  8. Repeat

Here is a full example program:

This program will keep adding one to A until it is not less than 5 each time it print out “in the while loop”. Once it exits the while loop it will set A to 0 and then print out “not in the while loop”.

The output:

in the while loop
in the while loop
in the while loop
in the while loop
in the while loop
not in the while loop
in the while loop
in the while loop
in the while loop
in the while loop
in the while loop
not in the while loop
….

 

For loops:

For loops are a special type of while loops. They are used to repeat for a specified amount of times.

The for loop has three parts to what is inside of the parentheses. The first step is to create a variable, this is the variable that will keep track of how many times we have looped through it. You can name it what you want, but the standard is to name it i. Then the second part is the condition, it will repeat while that is true, just like a while loop. Then the last part adds one to i (++ is the same as i = i + 1). This part of the code is done at the end of each loop. So the order of the for loop is:

  1. Create i (i is 0)
  2. Check if i is less than 5
  3. Run code
  4. Add 1 to i (i is 1)
  5. Check if i is less than 5
  6. Run code
  7. Add 1 to i (i is 2)
  8. Check if i is less than 5
  9. Repeat

So in a full code it would look like this:

This will have it print out the value of i until it is not less than 5. Once it is it will exit out of the for loop and print “out of the for loop”.

Output:

0
1
2
3
4
Out of the for loop
0
1
2
3
4
Out of the for loop
0
1

….