In programming we have something called a loop. A loop will continue to run (or loop) while a certain condition is satisfied. We can use a for loop when we want to loop (or repeat something) a known amount of times.
When we set up a for loop it looks something like this:
We can see that when we define our loop we need to include 3 pieces of information in the brackets.
1. Declare a counter (x = 0), this is what will be changing each run of the loop.
2. A condition (x < 5), the loop will only run while this condition is true.
3. An increment or decrement (x++). This is how much our counter will change by each loop.
In the example above our counter variable is x and it starts at a value of 0. Our condition is x < 5, meaning that the loop will continue to run while x is less than 5. Our increment is x++ which means x will increase by one each loop. Stepping through our loop we can see that once our loop has ran 5 times our x value is = to 5 meaning that we will not print 5 because x is not less than it.
Using For Loops on Arrays
Some of you may have noticed that running the following code does not produce the expected output.
We probably expect to see some kind output telling us the elements (1,5,6) of the array. But instead we see the following.
This is actually the memory address of the array and it most likely means nothing to us.
To print all of the elements of an array to the screen we can use a for loop!
Here is a few examples to help you understand for loops.