The general form of the for loop is as follows:-
for (initialization; condition; increment) statement sequence;
initialization;
This is generally an assignment statement used to set a loop control variable. e.g. i = 0
. Here I have set the loop control variable to an initial value of 10.
condition;
To determine when the loop exits you need some kind of condition, This is a relational statement such as i < 10
. This means loop until the value of i
reaches 10
.
increment
The increment defines how the loop control variable is changed each time the loop is repeated. e.g. i++
; This means increase i
by 1
every time the loop repeats.
Here it is in full, with each part separated by semi-colons:-
for (i = 0 ; i < 10; i++
) statement sequence;
This means set the initial value of i
to 0
. Then execute the statement sequence. Loop and increment the value of i
to 1
. Check the condition (that i
is still less than 10
which it is) and execute the statement sequence again, and so. The statement sequence is executed over and over again until i
finally reaches the value of 10
when the condition is reached and the loop is broken.
To put it simply, the for loop continues to execute until the condition becomes false. Then program execution continues on any line following the the for loop.
Now let's have a more concrete example. Suppose I want a program to display ten lines of the two times table on screen. The easiest way would be to use a for loop.
for (int
i = 1 ; i < 11; i++
) cout
<< i << " times 2 is " << (i * 2) << endl;
This prints out...
1 times 2 is 2
2 times 2 is 4
3 times 2 is 6
4 times 2 is 8
etc...
If I want more than one statement to be executed for every loop, all I have to do is enclose all the statements inside curly block brackets.
for (int
k = 10 ; k > 0; k--
) {
cout
<< "The square of " << k
<< " is " << k
*k
<< endl;
cout
<< ": The root of " << k
<< " is " << sqrt
(k
) << "\n";
}
Just for a change I called my loop control variable k
. If you want to run the code example above you will need to inlude the math.h
library file for the sqrt
function to be recognised.
Take note of the following points:-
- This time, for every loop I am decreasing the value of the loop control variable
k.
- I declared
k
inside the for loop. If you declare a variable inside the for statement then it is not available for use anywhere else in your code apart from inside the for block. In other words it is local to the for block.
Here is another for loop example:-
int
y;
cin >> y
;
for (int
x = 10; x<y; x += 2
) {
cout << "You have " << k
<< " seconds left." << endl;
}
Take note of the following points:-
- This loop may never execute at all if the user types in a value which sets
y
larger the 10
. This is because in a for loop, the conditional check is always carried out first before entering the loop.
- Also, this time
x
is incremented by 2
every time the for statement loops.
For Loop - Multiple Conditions
All the previous examples use a single loop control variable to control the loop. However, it is fairly common to use more than one loop control variable. As an example:-
For Loop - Missing Statement Parts
It is often useful to create a for loop with a missing increment section. Useful if say you want a loop to keep repeating until the user enters a particular input character. For example:-
for (char x = 0; x!= 'q';
) cin >> x;
Here, the increment section of the for is missing. The loop will keep repeating until the user enters the character q.
You can miss out other parts of the for loop statement. For example you may want to initialize the for loop outside the loop itself. In the following for loop, the loop control variable countdown
is initialized outside the for statement in order to get the user's input first.
int
countdown;
cin
>> countdown;
for ( ; countdown> 0 ; ) {
countdown--;
cout
<< countdown;
}
On running this, if I enter the number 6, I get...

For Loop - Infinite Loop
At some point in your programming activities you will probably create an infinite loop by accident, perhaps by incorrectly specifying the loop condition or because of an error in your logic. However, if you want to create an infinite for loop - here's how.
for ( ; ; ) cout
<< "stop me if you can\n";
Although this loop will run forever if allowed, you could insert a break
statement somewhere in the loop body to stop the loop:-
char
ch = '\0';
for ( ; ; ) {
cout
<< "please enter a character, or press q to quit\n";
cin
>> ch;
if
( ch == 'q' ) break
;
}
For Loop - No Body
for (int x = 0; x< 10; x++) ;
You could use a for loop without a body to create some kind of time delay. Here is an example:-
for (long
t = 0; t< 1000000; t++) ;
Although this may be useful on occasion - remember that your code may be run on different speed computers and this will not loop for the same period of time on each one. Look at the example below, I added extra code to see how long the for loop above runs on my PC.
#include
<time.h>
void
main() {
time_t
stime = time(NULL);
for (long
t = 0; t< 1000000000; t++) ;
time_t
etime = time(NULL);
cout
<< "time taken to loop was " << difftime(etime,stime) << " seconds";
}
The output was:-

You will probably get a different result.
~Now try the activity~
Activity 9A |
Here is a cute little for loop
for (char ch = '\0'; ch != 'q'; ) {
cout << "choose a piglet number from 1 to 5 or q to quit\n";
cin >> ch;
switch (ch){
case '1':
cout << "This little pig went to the market.\n\n";
break ;
case '2':
cout << "This little pig stayed home.\n\n";
break ;
case '3':
cout << "This little pig had roast beef.\n\n";
break;
case '4':
cout << "This little pig had none.\n\n";
break ;
case '5':
cout << "And this little pig went\n\t\tWee, wee, wee, wee, all the way home.\n\n";
break ;
default :
break ;
}
}
Now create a different version of this for loop where a single line of the rhyme is printed out for each repeat of the loop. Also, ask the user if they want to see the next line or quit every time. The program output should be similar to...
|