For Loops

A for loop allows us to repeat sections of code for a specified number of times, or iterations. There are 4 components that make up a for loop; the iterator, the condition, the increment and the code to be executed.

A for loop will repeat code for a specific number of times, therefore it must keep track of how many times it has done and when to stop. The iterator is the variable that stores the current number of times. We can also use the increment within the executed code, so we don’t have to start at 0, we could count from 10 up until 16. The iterator must be a number variable, it cannot be any other data type (string, character, boolean, etc).

The condition tells the for loop when to stop executing the code. If we are counting from 10 up until 16, then the condition would be when the iterator variable is less than or equal to the number 16. The condition must evaluate to a boolean value (true or false) and you can use any arithmetic operators within the condition.

The increment is how much we change the iterator by at the end of each looped interation. If we are counting from 10 to 16 then our increment may be to change to the iterator by 1 each time. We can also count in two’s by changing the increment to be plus two, rather than plus one. We are able to use the four basic arithmetic operators within the increment (addition, subtraction, multiplication and division).

Below are a few example of for loops to show the capability of them. Make sure you understand why and how the results are what they are, even if you don’t fully understand the code.

This piece of code will print out: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.

This piece of code will print out: 0, 2, 4, 6, 8, 10.

This piece of code will print out: 10, 11, 12, 13, 14, 15, 16.

This piece of code will print out: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1.

This piece of code will print out: 1, 2, 4, 8.

Leave a Reply