⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch07.htm

📁 一本好的VC学习书,本人就是使用这本书开始学习的vc,希望能对大家有帮助
💻 HTM
📖 第 1 页 / 共 5 页
字号:
In the <TT>do...while</TT> loop, the body of the loop is entered before the conditionis 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 online 15 the condition is tested. If the condition evaluates <TT>TRUE</TT>, executionjumps 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">dostatementwhile (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 areotherwise identical to the <TT>while</TT> loop. Example 1</P><PRE><FONT COLOR="#0066FF">// count to 10int x = 0;docout &lt;&lt; &quot;X: &quot; &lt;&lt; x++;while (x &lt; 10)</FONT></PRE><P>Example 2</P><PRE><FONT COLOR="#0066FF">// print lowercase alphabet.char ch = `a';do{cout &lt;&lt; ch &lt;&lt; ` `;ch++;} while ( ch &lt;= `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 astarting condition, testing to see if the condition is true, and incrementing orotherwise changing a variable each time through the loop. Listing 7.8 demonstratesthis.</P><P><A NAME="Heading32"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.8. While reexamined</B></FONT><FONTSIZE="2" COLOR="#000077"><B>.</B></FONT></P><PRE><FONT COLOR="#0066FF">1:    // Listing 7.82:    // Looping with while3:4:    #include &lt;iostream.h&gt;5:6:    int main()7:    {8:      int counter = 0;9:10:      while(counter &lt; 5)11:      {12:           counter++;13:           cout &lt;&lt; &quot;Looping!  &quot;;14:      }15:16:      cout &lt;&lt; &quot;\nCounter: &quot; &lt;&lt; counter &lt;&lt; &quot;.\n&quot;;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 line8: <TT>counter</TT> is initialized to <TT>0</TT>. On line 10, <TT>counter</TT> istested to see whether it is less than 5. <TT>counter</TT> is incremented on line12. On line 16, a simple message is printed, but you can imagine that more importantwork 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 areinitialization, 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 threestatements separated by semicolons.</P><P>The first statement is the initialization. Any legal C++ statement can be puthere, but typically this is used to create and initialize a counting variable. Statement2 is the test, and any legal C++ expression can be used here. This serves the samerole as the condition in the <TT>while</TT> loop. Statement 3 is the action. Typicallya value is incremented or decremented, though any legal C++ statement can be puthere. Note that statements 1 and 3 can be any legal C++ statement, but statement2 must be an expression--a C++ statement that returns a value. Listing 7.9 demonstratesa <TT>for</TT> loop.</P><P><A NAME="Heading34"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.9. Demonstratingthe for loop.</B></FONT></P><PRE><FONT COLOR="#0066FF">1:      // Listing 7.92:      // Looping with for3:4:      #include &lt;iostream.h&gt;5:6:      int main()7:      {8:        int counter;9:        for (counter = 0; counter &lt; 5; counter++)10:          cout &lt;&lt; &quot;Looping! &quot;;11:12:        cout &lt;&lt; &quot;\nCounter: &quot; &lt;&lt; counter &lt;&lt; &quot;.\n&quot;;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> statementon 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 bodyof the <TT>for</TT> statement is on line 9. Of course, a block could be used hereas 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 evaluatedeach time through the loop. If test is <TT>TRUE</TT>, the action in the header isexecuted (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 timesfor (int i = 0; i&lt;10; i++)cout &lt;&lt; &quot;Hello! &quot;;</FONT></PRE><P>Example 2</P><PRE><FONT COLOR="#0066FF">for (int i = 0; i &lt; 10; i++){    cout &lt;&lt; &quot;Hello!&quot; &lt;&lt; endl;    cout &lt;&lt; &quot;the value of i is: &quot; &lt;&lt; i &lt;&lt; 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 Initializationand Increments It is not uncommon to initialize more than one variable, to test acompound logical expression, and to execute more than one statement. The initializationand 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. Demonstratingmultiple statements in for loops.</B></FONT></P><PRE><FONT COLOR="#0066FF">1:  //listing 7.102:  // demonstrates multiple statements in3:  // for loops4:5: #include &lt;iostream.h&gt;6:7:  int main()8:  {9:      for (int i=0, j=0; i&lt;3; i++, j++)10:          cout &lt;&lt; &quot;i: &quot; &lt;&lt; i &lt;&lt; &quot; j: &quot; &lt;&lt; j &lt;&lt; endl;11:     return 0;<TT>12: }</TT></FONT><FONT COLOR="#0066FF">Output: i: 0  j: 0i: 1  j: 1i: 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&lt;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> statementis 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 truethe actions are repeated (<TT>i</TT> and <TT>j</TT> are again incremented), and thebody of loop is executed again. This continues until the test fails, in which casethe action statement is not executed, and control falls out of the loop. Null Statementsin for Loops Any or all of the statements in a <TT>for</TT> loop can be null. Toaccomplish this, use the semicolon to mark where the statement would have been. Tocreate a <TT>for</TT> loop that acts exactly like a <TT>while</TT> loop, leave outthe 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 statementsin for loops</B></FONT><FONT SIZE="2" COLOR="#000077"><B>.</B></FONT></P><PRE><FONT COLOR="#0066FF">1:    // Listing 7.112:    // For loops with null statements3:4:    #include &lt;iostream.h&gt;5:6:    int main()7:    {8:        int counter = 0;9:10:        for( ; counter &lt; 5; )11:        {12:           counter++;13:           cout &lt;&lt; &quot;Looping!  &quot;;14:        }15:16:        cout &lt;&lt; &quot;\nCounter: &quot; &lt;&lt; counter &lt;&lt; &quot;.\n&quot;;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 asexactly like the <TT>while</TT> loop illustrated in Listing 7.8! On line 8, the countervariable is initialized. The <TT>for</TT> statement on line 10 does not initializeany values, but it does include a test for <TT>counter &lt; 5</TT>. There is no incrementstatement, so this loop behaves exactly as if it had been written:</P><PRE><FONT COLOR="#0066FF">while (counter &lt; 5)</FONT></PRE><P>Once again, C++ gives you a number of ways to accomplish the same thing. No experiencedC++ programmer would use a <TT>for</TT> loop in this way, but it does illustratethe 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. Illustratingempty for loop statement.</B></FONT></P><PRE><FONT COLOR="#0066FF">1:     //Listing 7.12 illustrating2:     //empty for loop statement3:4:     #include &lt;iostream.h&gt;5:6:     int main()7:     {8:         int counter=0;       // initialization9:         int max;10:         cout &lt;&lt; &quot;How many hellos?&quot;;11:         cin &gt;&gt; max;12:         for (;;)          // a for loop that doesn't end13:         {14:            if (counter &lt; max)       // test15:            {16:              cout &lt;&lt; &quot;Hello!\n&quot;;17:              counter++;          // increment18:            }19:            else20:                break;21:         }22:        return 0;<TT>23: }</TT></FONT><FONT COLOR="#0066FF">Output: How many hellos?3Hello!Hello!Hello!</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The <TT>for</TT> loop hasnow been pushed to its absolute limit. Initialization, test, and action have allbeen taken out of the <TT>for</TT> statement. The initialization is done on line8, 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 line20.<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 exampleof a more reasonable use of such loops when <TT>switch</TT> statements are discussedlater 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 timesyou won't need the body to do anything at all. In that case, be sure to put a nullstatement (<TT>;</TT>) as the body of the loop. The semicolon can be on the sameline as the header, but this is easy to overlook. Listing 7.13 illustrates how touse a null body in a <TT>for</TT> loop.</P><P><A NAME="Heading45"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.13. Illustratesthe null statement in a for loop.</B></FONT></P><PRE><FONT COLOR="#0066FF">1:     //Listing 7.132:     //Demonstrates null statement3:     // as body of for loop4:5:     #include &lt;iostream.h&gt;6:     int main()7:     {8:        for (int i = 0; i&lt;5; cout &lt;&lt; &quot;i: &quot; &lt;&lt; i++ &lt;&lt; endl)9:        ;10:       return 0;<TT>11: }</TT></FONT><FONT COLOR="#0066FF">Output: i: 0i: 1i: 2i: 3i: 4</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The <TT>for</TT> loop online 8 includes three statements: the initialization statement establishes the counter<TT>i</TT> and initializes it to <TT>0</TT>. The condition statement tests for <TT>i&lt;5</TT>,and the action statement prints the value in <TT>i</TT> and increments it.<BR>There is nothing left to do in the body of the <TT>for</TT> loop, so the null statement(<TT>;</TT>) is used. Note that this is not a well-designed <TT>for</TT> loop: theaction statement is doing far too much. This would be better rewritten as</P><PRE><FONT COLOR="#0066FF">8:         for (int i = 0; i&lt;5; i++)</FONT></PRE><PRE><FONT COLOR="#0066FF">9:              cout &lt;&lt; &quot;i: &quot; &lt;&lt; i &lt;&lt; endl;</FONT></PRE><P><FONT COLOR="#0066FF"><BR></FONT>While both do exactly the same thing, this example is easier to understand.<H4 ALIGN="CENTER"><A NAME="Heading47"></A><FONT COLOR="#000077">Nested Loops</FONT></H4><P>Loops may be nested, with one loop sitting in the body of another. The inner loopwill be executed in full for every execution of the outer loop. Listing 7.14 illustrates

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -