for
The
for loop allows executing a
statement – or a block statement – for as many times as determined by
a conditional expression which is tested at the beginning of the
loop and at each iteration. Given the statement:
for(int i = 0; i < 5; i++)
cout << i << " ";
tthe statement
int i = 0;
}
Tis used to initialize the variable controlling the loop.
Such a statement is only executed once. The condition:
i < 5;
is tested right after the initialization statement has taken place.
If the condition evaluates to
true, the
for body (in this case the statement
cout << i << " ";) is executed. Afterwards,
the increment statement:
i++
is executed. Then the sequence restarts: the condition is checked, the body is
executed, the increment is executed, and so on; until the condition evaluates
to
false.
In case a loop needs to be exited before the condition evaluates to
false, the
break
statement can be used to force the execution thread to exit the loop.
For example, in the program below, the second for loop prints the numbers from
0 to 4 if the user agrees to it at each iteration. If the user disagrees by
inputting an 'n', the loop is exited by the
break statement.
Example
#include <iostream>
using namespace std;
int main()
{
for(int i = 0; i < 5; i++)
cout << i << " ";
cout << endl;
int j;
char c;
for(j = 0; j < 5; j++)
{
cout << "Print number? (y/n)";
cin >> c;
if(c == 'n')
break;
cout << j << endl;
}
if(j < 5)
cout << "The loop was broken out of";
}
(Possible) Output
0 1 2 3 4
Print number? (y/n)y
0
Print number? (y/n)y
1
Print number? (y/n)y
2
Print number? (y/n)n
The loop was broken out of