📄 ch07.htm
字号:
<TT>small</TT> is not bigger than <TT>large</TT>.<BR><BR><TT>large</TT> isn't negative.<BR><BR><TT>small</TT> doesn't overrun the size of a small integer (<TT>MAXSMALL</TT>).<BR><BR>On line 23, the value in <TT>small</TT> is calculated modulo 5,000. This does notchange the value in <TT>small</TT>; however, it only returns the value <TT>0</TT>when <TT>small</TT> is an exact multiple of 5,000. Each time it is, a dot (<TT>.</TT>)is printed to the screen to show progress. On line 26, <TT>small</TT> is incremented,and on line 28, <TT>large</TT> is decremented by 2.<BR>When any of the three conditions in the <TT>while</TT> loop fails, the loop endsand execution of the program continues after the <TT>while</TT> loop's closing braceon line 29.<BLOCKQUOTE> <P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>The modulus operator (%) and compound conditions are covered on Day 3, "Variables and Constants." <HR></BLOCKQUOTE><H4 ALIGN="CENTER"><A NAME="Heading16"></A><FONT COLOR="#000077">continue and break</FONT></H4><P>At times you'll want to return to the top of a <TT>while</TT> loop before theentire set of statements in the <TT>while</TT> loop is executed. The <TT>continue</TT>statement jumps back to the top of the loop.</P><P>At other times, you may want to exit the loop before the exit conditions are met.The <TT>break</TT> statement immediately exits the <TT>while</TT> loop, and programexecution resumes after the closing brace.</P><P>Listing 7.4 demonstrates the use of these statements. This time the game has becomemore complicated. The user is invited to enter a <TT>small</TT> number and a <TT>large</TT>number, a <TT>skip</TT> number, and a <TT>target</TT> number. The <TT>small</TT>number will be incremented by one, and the <TT>large</TT> number will be decrementedby 2. The decrement will be skipped each time the <TT>small</TT> number is a multipleof the <TT>skip</TT>. The game ends if <TT>small</TT> becomes larger than <TT>large</TT>.If the <TT>large</TT> number reaches the <TT>target</TT> exactly, a statement isprinted and the game stops.</P><P>The user's goal is to put in a target number for the <TT>large</TT> number thatwill stop the game.</P><P><A NAME="Heading17"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.4. break andcontinue.</B></FONT></P><PRE><FONT COLOR="#0066FF">1: // Listing 7.42: // Demonstrates break and continue3:4: #include <iostream.h>5:6: int main()7: {8: unsigned short small;9: unsigned long large;10: unsigned long skip;11: unsigned long target;12: const unsigned short MAXSMALL=65535;13:14: cout << "Enter a small number: ";15: cin >> small;16: cout << "Enter a large number: ";17: cin >> large;18: cout << "Enter a skip number: ";19: cin >> skip;20: cout << "Enter a target number: ";21: cin >> target;22:23: cout << "\n";24:25: // set up 3 stop conditions for the loop26: while (small < large && large > 0 && small < 65535)27:28: {29:30: small++;31:32: if (small % skip == 0) // skip the decrement?33: {34: cout << "skipping on " << small << endl;35: continue;36: }37:38: if (large == target) // exact match for the target?39: {40: cout << "Target reached!";41: break;42: }43:44: large-=2;45: } // end of while loop46:47: cout << "\nSmall: " << small << " Large: " << large << endl;48: return 0;<TT>49: }</TT>Output: Enter a small number: 2Enter a large number: 20Enter a skip number: 4Enter a target number: 6skipping on 4skipping on 8Small: 10 Large: 8</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis: </B></FONT>In this play, the user lost; <TT>small</TT>became larger than <TT>large</TT> before the <TT>target</TT> number of 6 was reached.<BR>On line 26, the <TT>while</TT> conditions are tested. If <TT>small</TT> continuesto be smaller than <TT>large</TT>, <TT>large</TT> is larger than 0, and <TT>small</TT>hasn't overrun the maximum value for a small <TT>int</TT>, the body of the <TT>while</TT>loop is entered.</P><P>On line 32, the <TT>small</TT> value is taken modulo the <TT>skip</TT> value.If <TT>small</TT> is a multiple of <TT>skip</TT>, the <TT>continue</TT> statementis reached and program execution jumps to the top of the loop at line 26. This effectivelyskips over the test for the <TT>target</TT> and the decrement of <TT>large</TT>.</P><P>On line 38, <TT>target</TT> is tested against the value for <TT>large</TT>. Ifthey are the same, the user has won. A message is printed and the <TT>break</TT>statement is reached. This causes an immediate break out of the <TT>while</TT> loop,and program execution resumes on line 46.<BLOCKQUOTE> <P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>Both <TT>continue</TT> and <TT>break</TT> should be used with caution. They are the next most dangerous commands after <TT>goto</TT>, for much the same reason. Programs that suddenly change direction are harder to understand, and liberal use of <TT>continue</TT> and <TT>break</TT> can render even a small <TT>while</TT> loop unreadable. <HR></BLOCKQUOTE><H3 ALIGN="CENTER"><A NAME="Heading19"></A><FONT COLOR="#000077">The continue Statement</FONT></H3><P><TT>continue;</TT> causes a <TT>while</TT> or <TT>for</TT> loop to begin againat the top of the loop. Example</P><PRE><FONT COLOR="#0066FF">if (value > 10) goto end;if (value < 10) goto end;cout << "value is 10!";end:cout << "done";</FONT></PRE><H3 ALIGN="CENTER"><A NAME="Heading20"></A><FONT COLOR="#000077">The break Statement</FONT></H3><P><TT>break;</TT> causes the immediate end of a <TT>while</TT> or <TT>for</TT> loop.Execution jumps to the closing brace. Example</P><PRE><FONT COLOR="#0066FF">while (condition){ if (condition2) break; // statements;}</FONT></PRE><H4 ALIGN="CENTER"><A NAME="Heading21"></A><FONT COLOR="#000077">while (1) Loops</FONT></H4><P>The condition tested in a <TT>while</TT> loop can be any valid C++ expression.As long as that condition remains true, the <TT>while</TT> loop will continue. Youcan create a loop that will never end by using the number 1 for the condition tobe tested. Since 1 is always true, the loop will never end, unless a <TT>break</TT>statement is reached. Listing 7.5 demonstrates counting to 10 using this construct.</P><P><A NAME="Heading22"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.5. while (1)loops.</B></FONT></P><PRE><FONT COLOR="#0066FF">1: // Listing 7.52: // Demonstrates a while true loop3:4: #include <iostream.h>5:6: int main()7: {8: int counter = 0;9:10: while (1)11: {12: counter ++;13: if (counter > 10)14: break;15: }16: cout << "Counter: " << counter << "\n";17: return 0;<TT>18: </TT>Output: Counter: 11</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>On line 10, a <TT>while</TT>loop is set up with a condition that can never be false. The loop increments the<TT>counter</TT> variable on line 12 and then on line 13 tests to see whether <TT>counter</TT>has gone past 10. If it hasn't, the <TT>while</TT> loop iterates. If <TT>counter</TT>is greater than 10, the <TT>break</TT> on line 14 ends the <TT>while</TT> loop, andprogram execution falls through to line 16, where the results are printed.<BR>This program works, but it isn't pretty. This is a good example of using the wrongtool for the job. The same thing can be accomplished by putting the test of <TT>counter</TT>'svalue where it belongs--in the <TT>while</TT> condition.<BLOCKQUOTE> <P><HR><FONT COLOR="#000077"><B>WARNING:</B></FONT><B> </B>Eternal loops such as <TT>while (1)</TT> can cause your computer to hang if the exit condition is never reached. Use these with caution and test them thoroughly. <HR></BLOCKQUOTE><P>C++ gives you many different ways to accomplish the same task. The real trickis picking the right tool for the particular job.<BLOCKQUOTE> <P><HR><B>DON'T</B> use the <TT>goto</TT> statement. <B>DO</B> use <TT>while</TT> loops to iterate while a condition is true. <B>DO</B> exercise caution when using <TT>continue</TT> and <TT>break </TT>statements. <B>DO</B> make sure your loop will eventually end. <HR></BLOCKQUOTE><H3 ALIGN="CENTER"><A NAME="Heading24"></A><FONT COLOR="#000077">do...while Loops</FONT></H3><P>It is possible that the body of a <TT>while</TT> loop will never execute. The<TT>while</TT> statement checks its condition before executing any of its statements,and if the condition evaluates <TT>false</TT>, the entire body of the <TT>while</TT>loop is skipped. Listing 7.6 illustrates this.</P><P><A NAME="Heading25"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.6. Skippingthe body of the while Loop</B></FONT><FONT SIZE="2" COLOR="#000077"><B>.</B></FONT></P><PRE><FONT COLOR="#0066FF">1: // Listing 7.62: // Demonstrates skipping the body of3: // the while loop when the condition is false.4:5: #include <iostream.h>6:7: int main()8: {9: int counter;10: cout << "How many hellos?: ";11: cin >> counter;12: while (counter > 0)13: {14: cout << "Hello!\n";15: counter--;16: }17: cout << "Counter is OutPut: " << counter;18: return 0;<TT>19: }</TT>Output: How many hellos?: 2Hello!Hello!Counter is OutPut: 0How many hellos?: 0Counter is OutPut: 0</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The user is prompted fora starting value on line 10. This starting value is stored in the integer variable<TT>counter</TT>. The value of <TT>counter</TT> is tested on line 12, and decrementedin the body of the <TT>while</TT> loop. The first time through <TT>counter</TT> wasset to <TT>2</TT>, and so the body of the <TT>while</TT> loop ran twice. The secondtime through, however, the user typed in <TT>0</TT>. The value of <TT>counter</TT>was tested on line 12 and the condition was false; <TT>counter</TT> was not greaterthan <TT>0</TT>. The entire body of the <TT>while</TT> loop was skipped, and <TT>Hello</TT>was never printed.<BR>What if you want to ensure that <TT>Hello</TT> is always printed at least once? The<TT>while</TT> loop can't accomplish this, because the <TT>if</TT> condition is testedbefore any printing is done. You can force the issue with an <TT>if</TT> statementjust before entering the <TT>while</TT>:</P><PRE><FONT COLOR="#0066FF">if (counter < 1) // force a minimum valuecounter = 1;</FONT></PRE><P>but that is what programmers call a "kludge," an ugly and inelegantsolution.<H3 ALIGN="CENTER"><A NAME="Heading27"></A><FONT COLOR="#000077">do...while</FONT></H3><P>The <TT>do...while</TT> loop executes the body of the loop before its conditionis tested and ensures that the body always executes at least one time. Listing 7.7rewrites Listing 7.6, this time using a <TT>do...while</TT> loop.</P><P><A NAME="Heading28"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 7.7. Demonstratesdo...while loop.</B></FONT></P><PRE><FONT COLOR="#0066FF">1: // Listing 7.72: // Demonstrates do while3:4: #include <iostream.h>5:6: int main()7: {8: int counter;9: cout << "How many hellos? ";10: cin >> counter;11: do12: {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? 2HelloHelloCounter is: 0</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The user is prompted fora starting value on line 9, which is stored in the integer variable <TT>counter</TT>.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -