Loops
This page is a continuation to the explanation of control flow here. Loops are extremely useful control flow statements that save time programming and make our code easier to read and debug. We’ll go over the multiple types of loops and their differences in this page.
While Loops
The while
loop is the simplest loop and is used to repeat a part of the program repeatedly until the specified Boolean condition is false. As soon as the Boolean condition becomes false, the loop automatically stops.
Here is the structure of a while loop:
while (condition) { // the condition that is evaluated to true or false
// Do things here
// Last line of the loop body is the one right before the }
}
Let’s go over how this loop will be executed:
- The condition is evaluated. If it evaluates to
false
, the code is skipped. - Loop body is executed only if the condition evaluates to
true
- Repeats
If the condition switches from evaluating to
true
to evaluating tofalse
during step 2, the while loop won’t stop until it ends and repeats step 1.
For Loops
Another common loop is the for loop. The for loop is useful when you need to loop through a set number of items. Let’s say we want to loop through a set of numbers to add them up, here is how you would do it:
int number = 3;
for (int i = 0; i < 10; i++) { // <- Important line!
number = number + i;
// Once again, the last line of the loop body is the one right before the }
}
The line containing the for
statement itself contains several statements, let’s break them down:
-
int i = 0;
- This is run before the first iteration of the loop and sets the variable that the rest of the loop uses. This variable is usually named after a single letter such as
i
orj
.
- This is run before the first iteration of the loop and sets the variable that the rest of the loop uses. This variable is usually named after a single letter such as
-
i < 10;
- A condition utilizing equality operators. If this condition is true, the loop runs again, otherwise the program moves on. This is identical to the while loop’s condition that we saw above.
-
i++;
- Ran at the end of each iteration of the for loop, and in this specific example is utilizing math shorthand to increment
i
by 1
- Ran at the end of each iteration of the for loop, and in this specific example is utilizing math shorthand to increment
Finally, you have the actual code which is run each iteration. Notice we reference the variable i
in the code.
One detail worth noting is that the for loop and while loop can both accomplish the same tasks. It is just a clearer and more convenient way to do many tasks. Here is what the above for loop example would look like as a while loop:
int number = 0;
int i = 0;
while (i < 10) { // the condition that is evaluated
number = number + 1;
i++; //or i = i + 1;
// Last line of the loop body is the one right before the }
}