In earlier lessons we went over while and do while loops and learned in what cases we would use them. In this lesson, we will be going over a new loop called a for loop. For loops typically serve a much more specific role, than other loops. Let’s look over the outline of one:
There are 3 different sections within the parenthesis of a for loop that are each separated by a semicolon.
Section 1 is executed first and assigns a numerical value (typically to an int.)
Section 2 is the condition that must be met to have the loop continue to run.
Section 3 has an increment or decrement operator associated with the value in section 1.
Then, just like other loops we learned about, we put whatever code we want repeated every loop inside of the curly brackets.
Now that we have a rough idea of what a for loop should look like, let’s look at an actual for loop in action.
In the code above, we have a program that is designed to count to the number 10. Within the first section of our for loop, we assign the int value
i to start at the number 1.
In the 2nd section, we have the condition that while
i is less than or equal to the count number, the loop will continue to run.
In the third section, we have the increment operator that will add 1 to
i for every loop.
Finally, within our brackets we tell the computer to print out
i every time it loops. After compiling and running the program, we get the following output:
Just like we hoped, the program tells us what number it is counting to and stops after reaching it. Great job and see you next lesson!