?? ch07.htm
字號:
5:
6: int main()
7: {
8: int counter;
9: cout << "How many hellos? ";
10: cin >> counter;
11: do
12: {
13: cout << "Hello\n";
14: counter--;
15: } while (counter >0 );
16: cout << "Counter is: " << counter << endl;
17: return 0;
<TT>18: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: How many hellos? 2
Hello
Hello
Counter is: 0
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The user is prompted for
a starting value on line 9, which is stored in the integer variable <TT>counter</TT>.
In the <TT>do...while</TT> loop, the body of the loop is entered before the condition
is tested, and therefore the body of the loop is guaranteed to run at least once.
On line 13 the message is printed, on line 14 the counter is decremented, and on
line 15 the condition is tested. If the condition evaluates <TT>TRUE</TT>, execution
jumps to the top of the loop on line 13; otherwise, it falls through to line 16.<BR>
The <TT>continue</TT> and <TT>break</TT> statements work in the <TT>do...while</TT>
loop exactly as they do in the <TT>while</TT> loop. The only difference between a
<TT>while</TT> loop and a <TT>do...while</TT> loop is when the <TT>condition</TT>
is tested.
<H3 ALIGN="CENTER"><A NAME="Heading30"></A><FONT COLOR="#000077">The do...while Statement</FONT></H3>
<P>The syntax for the <TT>do...while</TT> statement is as follows:</P>
<PRE><FONT COLOR="#0066FF">do
statement
while (condition);
</FONT></PRE>
<P>statement is executed, and then condition is evaluated. If condition is <TT>TRUE</TT>,
the loop is repeated; otherwise, the loop ends. The statements and conditions are
otherwise identical to the <TT>while</TT> loop. Example 1</P>
<PRE><FONT COLOR="#0066FF">// count to 10
int x = 0;
do
cout << "X: " << x++;
while (x < 10)
</FONT></PRE>
<P>Example 2</P>
<PRE><FONT COLOR="#0066FF">// print lowercase alphabet.
char ch = `a';
do
{
cout << ch << ` `;
ch++;
} while ( ch <= `z' );
</FONT></PRE>
<BLOCKQUOTE>
<P>
<HR>
<B>DO</B> use <TT>do...while</TT> when you want to ensure the loop is executed at
least once. <B>DO </B>use <TT>while</TT> loops when you want to skip the loop if
the condition is false. <B>DO</B> test all loops to make sure they do what you expect.
<HR>
</BLOCKQUOTE>
<H3 ALIGN="CENTER"><A NAME="Heading31"></A><FONT COLOR="#000077">for Loops</FONT></H3>
<P>When programming <TT>while</TT> 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.</P>
<P><A NAME="Heading32"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.8. While reexamined</B></FONT><FONT
SIZE="2" COLOR="#000077"><B>.</B></FONT></P>
<PRE><FONT COLOR="#0066FF">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;
<TT>18: }</TT>
Output: Looping! Looping! Looping! Looping! Looping!
Counter: 5.
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The condition is set on line
8: <TT>counter</TT> is initialized to <TT>0</TT>. On line 10, <TT>counter</TT> is
tested to see whether it is less than 5. <TT>counter</TT> 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 <TT>counter</TT>.<BR>
A <TT>for</TT> loop combines three steps into one statement. The three steps are
initialization, test, and increment. A <TT>for</TT> statement consists of the keyword
<TT>for</TT> followed by a pair of parentheses. Within the parentheses are three
statements separated by semicolons.</P>
<P>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 <TT>while</TT> 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 <TT>for</TT> loop.</P>
<P><A NAME="Heading34"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.9. Demonstrating
the for loop.</B></FONT></P>
<PRE><FONT COLOR="#0066FF">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;
<TT>14: }</TT></FONT>
<FONT COLOR="#0066FF">Output: Looping! Looping! Looping! Looping! Looping!
Counter: 5.
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The <TT>for</TT> statement
on line 8 combines the initialization of <TT>counter</TT>, the test that <TT>counter</TT>
is less than 5, and the increment of <TT>counter</TT> all into one line. The body
of the <TT>for</TT> statement is on line 9. Of course, a block could be used here
as well.
<H3 ALIGN="CENTER"><A NAME="Heading36"></A><FONT COLOR="#000077">The for Statement</FONT></H3>
<P>The syntax for the <TT>for</TT> statement is as follows:</P>
<PRE><FONT COLOR="#0066FF">for (initialization; test; action )
statement;
</FONT></PRE>
<P>The initialization statement is used to initialize the state of a <TT>counter</TT>,
or to otherwise prepare for the loop. test is any C++ expression and is evaluated
each time through the loop. If test is <TT>TRUE</TT>, the action in the header is
executed (typically the counter is incremented) and then the body of the <TT>for</TT>
loop is executed. Example 1</P>
<PRE><FONT COLOR="#0066FF">// print Hello ten times
for (int i = 0; i<10; i++)
cout << "Hello! ";
</FONT></PRE>
<P>Example 2</P>
<PRE><FONT COLOR="#0066FF">for (int i = 0; i < 10; i++)
{
cout << "Hello!" << endl;
cout << "the value of i is: " << i << endl;
}
</FONT></PRE>
<H4 ALIGN="CENTER"><A NAME="Heading37"></A><FONT COLOR="#000077">Advanced for Loops</FONT></H4>
<P><TT>for</TT> statements are powerful and flexible. The three independent statements
(initialization, test, and action) lend themselves to a number of variations.</P>
<P>A <TT>for</TT> loop works in the following sequence:
<DL>
<DD><B>1.</B> Performs the operations in the initialization.<BR>
<BR>
<B>2.</B> Evaluates the condition.<BR>
<BR>
<B>3.</B> If the condition is <TT>TRUE</TT>, executes the action statement and the
loop.
</DL>
<P>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.</P>
<P><A NAME="Heading38"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.10. Demonstrating
multiple statements in for loops.</B></FONT></P>
<PRE><FONT COLOR="#0066FF">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;
<TT>12: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: i: 0 j: 0
i: 1 j: 1
i: 2 j: 2
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis: </B></FONT>On line 9, two variables, <TT>i</TT>
and <TT>j</TT>, are each initialized with the value <TT>0</TT>. The test (<TT>i<3</TT>)
is evaluated, and because it is true, the body of the <TT>for</TT> statement is executed,
and the values are printed. Finally, the third clause in the <TT>for</TT> statement
is executed, and <TT>i</TT> and <TT>j</TT> are incremented.<BR>
Once line 10 completes, the condition is evaluated again, and if it remains true
the actions are repeated (<TT>i</TT> and <TT>j</TT> 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 <TT>for</TT> loop can be null. To
accomplish this, use the semicolon to mark where the statement would have been. To
create a <TT>for</TT> loop that acts exactly like a <TT>while</TT> loop, leave out
the first and third statements. Listing 7.11 illustrates this idea.</P>
<P><A NAME="Heading40"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.11. Null statements
in for loops</B></FONT><FONT SIZE="2" COLOR="#000077"><B>.</B></FONT></P>
<PRE><FONT COLOR="#0066FF">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;
<TT>18: }</TT></FONT>
<FONT COLOR="#0066FF">
output: Looping! Looping! Looping! Looping! Looping!
Counter: 5.
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>You may recognize this as
exactly like the <TT>while</TT> loop illustrated in Listing 7.8! On line 8, the counter
variable is initialized. The <TT>for</TT> statement on line 10 does not initialize
any values, but it does include a test for <TT>counter < 5</TT>. There is no increment
statement, so this loop behaves exactly as if it had been written:</P>
<PRE><FONT COLOR="#0066FF">while (counter < 5)</FONT></PRE>
<P>Once again, C++ gives you a number of ways to accomplish the same thing. No experienced
C++ programmer would use a <TT>for</TT> loop in this way, but it does illustrate
the flexibility of the <TT>for</TT> statement. In fact, it is possible, using <TT>break</TT>
and <TT>continue</TT>, to create a <TT>for</TT> loop with none of the three statements.
Listing 7.12 illustrates how.</P>
<P><A NAME="Heading42"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.12. Illustrating
empty for loop statement.</B></FONT></P>
<PRE><FONT COLOR="#0066FF">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;
<TT>23: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: How many hellos?3
Hello!
Hello!
Hello!
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The <TT>for</TT> loop has
now been pushed to its absolute limit. Initialization, test, and action have all
been taken out of the <TT>for</TT> statement. The initialization is done on line
8, before the <TT>for</TT> loop begins. The test is done in a separate <TT>if</TT>
statement on line 14, and if the test succeeds, the action, an increment to <TT>counter</TT>,
is performed on line 17. If the test fails, breaking out of the loop occurs on line
20.<BR>
While this particular program is somewhat absurd, there are times when a <TT>for(;;)</TT>
loop or a <TT>while (1)</TT> loop is just what you'll want. You'll see an example
of a more reasonable use of such loops when <TT>switch</TT> statements are discussed
later today.
<H4 ALIGN="CENTER"><A NAME="Heading44"></A><FONT COLOR="#000077">Empty for Loops</FONT></H4>
<P>So much can be done in the header of a <TT>for</TT> 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 (<TT>;</TT>) 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 <TT>for</TT> loop.</P>
<P><A NAME="Heading45"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.13. Illustrates
the null statement in a for loop.</B></FONT></P>
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -