For Loops
Video Summary: https://youtu.be/VQ_d6KiUNRo
The for
statement is a looping structure designed
specifically to simplify the implementation of count-controlled loops
(That is, a count-controlled while
loop can be replaced by a for
loop.).
The loop-control variable, the beginning value, the ending value, and
the incrementation are explicitly part of the for
loop heading itself.
The syntax template for a for
statement is
for (Init_Statement; Boolean_Expression; Update_Expression)
{
// Statements
}
Each part inside the ()
parentheses of the for
loop can be any line of code, but usually they are used like this:
- The Init_Statement usually initializes a loop control variable. It can also declare the variable. If it does, the variable's scope ends with the loop.
- The Boolean_Expression is equivalent to a
while
condition. - The Update_Expression usually increments or decrements the loop control variable.
The following for
loop reads 10 marks and sums them up.
int sum = 0; for (int counter = 1; counter <= 10; counter++) { cout << "Please enter a mark: "; cin >> mark; sum = sum + mark; }
The following for
loop also reads 10 marks and sums them up.
int sum = 0; for (int counter = 10; counter > 0; counter--) { cout << "Please enter a mark: "; cin >> mark; sum = sum + mark; }
Of course, all for
loops can be written as count-controlled while
loops.
For example, we can change the previous program segment to the following
equivalent piece of code.
int sum = 0; int counter = 1; while(counter <= 10) { cout << "Please enter a mark: "; cin >> mark; sum = sum + mark; counter++; }