|

When
programming while loops, you’ll often find yourself
setting up a starting condition, testing to see
if the condition is true, and incrementing or otherwise
changing a variable each time through the loop.
Listing 7.8 demonstrates this.
Listing
7.8. While reexamined.
1:
// Listing 7.8
2:
// Looping with while
3:
4:
#include <iostream.h>
5:
6:
int main()
7:
{
8:
int counter = 0;
9:
10:
while(counter < 5)
11:
{
12:
counter++;
13:
cout << "Looping! ";
14:
}
15:
16:
cout << "\nCounter: " << counter <<
".\n";
17:
return 0;
18:
}
Output:
Looping! Looping! Looping! Looping! Looping!
Counter: 5.
Analysis: The condition is set on line
8: counter is initialized to 0. On line 10, counter
is tested to see whether it is less than 5. counter
is incremented on line 12. On line 16, a simple
message is printed, but you can imagine that more
important work could be done for each increment
of the counter. A for loop combines three steps
into one statement. The three steps are initialization,
test, and increment. A for statement consists of
the keyword for followed by a pair of parentheses.
Within the parentheses are three statements separated
by semicolons.
The
first statement is the initialization. Any legal
C++ statement can be put here, but typically this
is used to create and initialize a counting variable.
Statement 2 is the test, and any legal C++ expression
can be used here. This serves the same role as the
condition in the while loop. Statement 3 is the
action. Typically a value is incremented or decremented,
though any legal C++ statement can be put here.
Note that statements 1 and 3 can be any legal C++
statement, but statement 2 must be an expression—a
C++ statement that returns a value. Listing 7.9
demonstrates a for loop.
Listing
7.9. Demonstrating the for loop.
1:
// Listing 7.9
2:
// Looping with for
3:
4:
#include <iostream.h>
5:
6:
int main()
7:
{
8:
int counter;
9:
for (counter = 0; counter < 5; counter++)
10:
cout << "Looping! ";
11:
12:
cout << "\nCounter: " << counter <<
".\n";
13:
return 0;
14:
}
Output:
Looping! Looping! Looping! Looping! Looping!
Counter: 5.
Analysis: The for statement on line
8 combines the initialization of counter, the test
that counter is less than 5, and the increment of
counter all into one line. The body of the for statement
is on line 9. Of course, a block could be used here
as well.
The
for Statement
The
syntax for the for statement is as follows:
|
for
(initialization; test; action )
statement;
|
The
initialization statement is used to initialize the
state of a counter, or to otherwise prepare for
the loop. test is any C++ expression and is evaluated
each time through the loop. If test is TRUE, the
action in the header is executed (typically the
counter is incremented) and then the body of the
for loop is executed.
Example
1
//
print Hello ten times
for
(int i = 0; i<10; i++)
cout
<< "Hello! ";
Example
2
for
(int i = 0; i < 10; i++)
{
cout
<< "Hello!" << endl;
cout
<< "the value of i is: " << i <<
endl;
}
Advanced
for Loops
for
statements are powerful and flexible. The three
independent statements (initialization, test, and
action) lend themselves to a number of variations.
A
for loop works in the following sequence:
1.
Performs the operations in the initialization.
2.
Evaluates the condition.
3.
If the condition is TRUE, executes the action statement
and the loop.
After
each time through, the loop repeats steps 2 and
3. Multiple Initialization and Increments It is
not uncommon to initialize more than one variable,
to test a compound logical expression, and to execute
more than one statement. The initialization and
the action may be replaced by multiple C++ statements,
each separated by a comma. Listing 7.10 demonstrates
the initialization and increment of two variables.
Listing
7.10. Demonstrating multiple statements in for
loops.
1:
//listing 7.10
2:
// demonstrates multiple statements in
3:
// for loops
4:
5:
#include <iostream.h>
6:
7:
int main()
8:
{
9:
for (int i=0, j=0; i<3; i++, j++)
10:
cout << "i: " << i << " j: " <<
j << endl;
11:
return 0;
12:
}
Output:
i: 0 j: 0
i: 1 j: 1
i: 2 j: 2
Analysis: On line 9, two variables,
i and j, are each initialized with the value 0.
The test (i<3) is evaluated, and because it is
true, the body of the for statement is executed,
and the values are printed. Finally, the third clause
in the for statement is executed, and i and j are
incremented.
Once line 10 completes, the condition is evaluated
again, and if it remains true the actions are repeated
(i and j are again incremented), and the body of
loop is executed again. This continues until the
test fails, in which case the action statement is
not executed, and control falls out of the loop.
Null Statements in for Loops Any or all of the statements
in a for loop can be null. To accomplish this, use
the semicolon to mark where the statement would
have been. To create a for loop that acts exactly
like a while loop, leave out the first and third
statements. Listing 7.11 illustrates this idea.
Listing
7.11. Null statements in for loops.
1:
// Listing 7.11
2:
// For loops with null statements
3:
4:
#include <iostream.h>
5:
6:
int main()
7:
{
8:
int counter = 0;
9:
10:
for( ; counter < 5; )
11:
{
12:
counter++;
13:
cout << "Looping! ";
14:
}
15:
16:
cout << "\nCounter: " << counter <<
".\n";
17:
return 0;
18:
}
output:
Looping! Looping! Looping! Looping! Looping!
Counter: 5.
Analysis: You may recognize this as
exactly like the while loop illustrated in Listing
7.8! On line 8, the counter variable is initialized.
The for statement on line 10 does not initialize
any values, but it does include a test for counter
< 5. There is no increment statement, so this
loop behaves exactly as if it had been written:
while
(counter < 5)
Once
again, C++ gives you a number of ways to accomplish
the same thing. No experienced C++ programmer would
use a for loop in this way, but it does illustrate
the flexibility of the for statement. In fact, it
is possible, using break and continue, to create
a for loop with none of the three statements. Listing
7.12 illustrates how.
Listing
7.12. Illustrating empty for loop statement.
1:
//Listing 7.12 illustrating
2:
//empty for loop statement
3:
4:
#include <iostream.h>
5:
6:
int main()
7:
{
8:
int counter=0; // initialization
9:
int max;
10:
cout << "How many hellos?";
11:
cin >> max;
12:
for (;;) // a for loop that doesn’t end
13:
{
14:
if (counter < max) // test
15:
{
16:
cout << "Hello!\n";
17:
counter++; // increment
18:
}
19:
else
20:
break;
21:
}
22:
return 0;
23:
}
Output:
How many hellos?3
Hello!
Hello!
Hello!
Analysis: The for loop has now been
pushed to its absolute limit. Initialization, test,
and action have all been taken out of the for statement.
The initialization is done on line 8, before the
for loop begins. The test is done in a separate
if statement on line 14, and if the test succeeds,
the action, an increment to counter, is performed
on line 17. If the test fails, breaking out of the
loop occurs on line 20. While this particular program
is somewhat absurd, there are times when a for(;;)
loop or a while (1) loop is just what you’ll want.
You’ll see an example of a more reasonable use of
such loops when switch statements are discussed
later.
Empty
for Loops
So
much can be done in the header of a for statement,
there are times you won’t need the body to do anything
at all. In that case, be sure to put a null statement
(;) as the body of the loop. The semicolon can be
on the same line as the header, but this is easy
to overlook. Listing 7.13 illustrates how to use
a null body in a for loop.
Listing
7.13. Illustrates the null statement in a for
loop.
1:
//Listing 7.13
2:
//Demonstrates null statement
3:
// as body of for loop
4:
5:
#include <iostream.h>
6:
int main()
7:
{
8:
for (int i = 0; i<5; cout << "i: " <<
i++ << endl)
9:
;
10:
return 0;
11:
}
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
Analysis: The for loop on line 8 includes
three statements: the initialization statement establishes
the counter i and initializes it to 0. The condition
statement tests for i<5, and the action statement
prints the value in i and increments it. There is
nothing left to do in the body of the for loop,
so the null statement (;) is used. Note that this
is not a well-designed for loop: the action statement
is doing far too much. This would be better rewritten
as
8:
for (int i = 0; i<5; i++)
9:
cout << "i: " << i << endl;
While
both do exactly the same thing, this example is
easier to understand.
|