Sams Teach Yourself C++ in 21 Days

(singke) #1
More on Program Flow 179

7


Exploring More Complicated whileStatements............................................


The condition tested by a whileloop can be as complex as any legal C++ expression.
This can include expressions produced using the logical &&(AND),||(OR), and!
(NOT) operators. Listing 7.3 is a somewhat more complicated whilestatement.

LISTING7.3 Complex whileLoops


1: // Listing 7.3
2: // Complex while statements
3: #include <iostream>
4:
5: int main()
6: {
7: using namespace std;
8: unsigned short small;
9: unsigned long large;
10: const unsigned short MAXSMALL=65535;
11:
12: cout << “Enter a small number: “;
13: cin >> small;
14: cout << “Enter a large number: “;
15: cin >> large;
16:
17: cout << “small: “ << small << “...”;
18:
19: // for each iteration, test two conditions
20: while (small < large && small < MAXSMALL)
21: {
22: if (small % 5000 == 0) // write a dot every 5k lines
23: cout << “.”;
24:
25: small++;
26: large-=2;
27: }
28:
29: cout << “\nSmall: “ << small << “ Large: “ << large << endl;
30: return 0;
31: }

Enter a small number: 2
Enter a large number: 100000
small: 2.........
Small: 33335 Large: 33334
This program is a game. Enter two numbers, one small and one large. The
smaller number will count up by ones, and the larger number will count down by
twos. The goal of the game is to guess when they’ll meet.

OUTPUT


ANALYSIS
Free download pdf