while Loops

Demonstrated in Listing 6.1, a while loop causes your program to repeat a sequence of statements as long as the starting condition remains true.

Listing 6.1. while Loops
 0:  // Listing 6.1
 1:  // Looping with while
 2:  #include <iostream>
 3:
 4:  int main()
 5:  {
 6:      int counter = 0;            // initialize the condition
 7:
 8:      while(counter < 5)          // test condition still true
 9:      {
10:          counter++;              // body of the loop
11:          std::cout << "counter: " << counter << "
";
12:      }
13:
14:      std::cout << "Complete. counter: " << counter << ".
";
15:      return 0;
16:  }


counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
Complete. counter: 5

This simple program demonstrates the fundamentals of the while loop. A condition is tested, and if it is true, the body of the while loop is executed. In this case, the condition tested on line 8 is whether counter is less than 5. If the condition is true, the body of the loop is executed. On line 10, the counter is incremented, and on line 11 the value is printed. When the conditional statement on line 8 fails (when counter is no longer less than 5), the entire body of the while loop (on lines 9–12) is skipped. Program execution falls through to line 14.


More Complicated while Statements

The condition tested by a while loop can be as complex as any legal C++ expression. This can include expressions produced using the logical && (and), || (or), and ! (not) operators. Listing 6.2 is a somewhat more complicated while statement.

Listing 6.2. Complex while Loops
 0:  // Listing 6.2
 1:  // Complex while statements
 2:  #include <iostream>
 3:
 4:  int main()
 5:  {
 6:      unsigned short small;
 7:      unsigned long  large;
 8:      const unsigned short MAXSMALL=65535;
 9:
10:      std::cout << "Enter a small number: ";
11:      std::cin >> small;
12:      std::cout << "Enter a large number: ";
13:      std::cin >> large;
14:
15:      std::cout << "small: " << small << "...";
16:

17:       // for each iteration, test three conditions
18:      while (small < large && large > 0 && small < MAXSMALL)
19:
20:      {
21:          if (small % 5000 == 0)  // write a dot every 5k lines
22:              std::cout << ".";
23:
24:          small++;
25:
26:          large-=2;
27:      }
28:
29:      std::cout <<"
Small: " << small
30:                << " Large: "  << large << std::endl;
31:      return 0;
32:  }


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; the larger number will count down by twos. The goal of the game is to guess when they'll meet. On lines 10–13, the numbers are entered. Line 18 sets up a while loop, which will continue only as long as three conditions are met:


  • small is not bigger than large.

  • large isn't negative.

  • small doesn't overrun the size of a small integer (MAXSMALL).

On line 21 the value in small is calculated modulo 5,000. Since the modulo is the remainder, it only returns the value 0 when small is an exact multiple of 5,000. Remember that this does not change the value in small. Each time the value is 0, a dot (.) is printed to the screen to show progress. On line 24, small is incremented, and on line 26 large is decremented by 2.

When any of the three conditions in the while loop fails, the loop ends and execution of the program continues after the while loop's closing brace, on line 29.

continue and break

At times, you'll want to return to the top of a while loop before the entire set of statements in the while loop is executed. The continue statement jumps back to the top of the loop.

At other times, you might want to exit the loop before the exit conditions are met. The break statement immediately exits the while loop, and program execution resumes after the closing brace.

Listing 6.3 demonstrates the use of these statements. This time the game has become more complicated. The user is invited to enter a small number, a large number, a skip number, and a target number. The small number will be incremented by 1, and the large number will be decremented by 2. The decrement will be skipped each time the small number is a multiple of the skip. The game ends if small becomes larger than large. If the large number reaches the target exactly, a statement is printed and the game stops.

The user's goal is to put in a target number for the large number that will stop the game.

Listing 6.3. break and continue
0:  // Listing 6.3
  1:  // Demonstrates break and continue
  2:  #include <iostream>
  3:  using namespace std;// this file uses std::cout,
  4:                      // std::cin, std::endl, etc.
  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 << "
";
 24:
 25:      // set up 3 stop conditions for the loop
 26:      while (small < large && large > 0 && small < 65535)
 27:      {
 28:          small++;
 29:
 30:          if (small % skip == 0)// skip the decrement?
 31:          {
 32:              cout << "skipping on " << small << endl;
 33:              continue;
 34:          }
 35:
 36:          if (large == target)  // exact match for the target?
 37:          {
 38:              cout << "Target reached!";
 39:              break;
 40:          }
 41:
 42:          large-=2;
 43:      }                          // end of while loop
 44:
 45:      cout << "
Small: " << small << " Large: " <<  large << endl;
 46:      return 0;
 47:  }


Enter a small number: 2
Enter a large number: 20
Enter a skip number: 4
Enter a target number: 6
skipping on 4
skipping on 8
Small: 10 Large: 8
						

In this play, the user lost; small became larger than large before the target number of 6 was reached.


On line 26, the while conditions are tested. If small continues to be smaller than large, large is larger than 0, and small hasn't overrun the maximum value for an unsigned short int, the body of the while loop is entered.

On line 30, the small value is taken modulo the skip value. If small is a multiple of skip, the continue statement is reached and program execution jumps to the top of the loop at line 26. This effectively skips over the test for the target and the decrement of large.

On line 36, target is tested against the value for large. If they are the same, the user has won. A message is printed, and the break statement is reached. This causes an immediate break out of the while loop, and program execution resumes on line 45.

Both continue and break should be used with caution. Programs that suddenly branch from within the middle of loops are harder to understand, and liberal use of continue and break can render even a small while loop unreadable.

while(1) Loops

The condition tested in a while loop can be any valid C++ expression. As long as that condition remains true, the while loop will continue. You can create a loop that will never end by using the number 1 for the condition to be tested. Because 1 is always true, the loop will never end, unless a break statement is reached. Listing 6.4 demonstrates counting to 10 using this construct.

Listing 6.4. while(1) Loops
 0:  // Listing 6.4
 1:  // Demonstrates a while true loop
 2:  #include <iostream>
 3:
 4:  int main()
 5:  {
 6:      int counter = 0;
 7:
 8:      while (1)
 9:      {
10:          counter ++;
11:          if (counter > 10)
12:              break;
13:      }
14:      std::cout << "counter: " << counter << "
";
15:      return 0;
16:  }


counter: 11

On line 8, a while loop is set up with a condition that can never be false. The loop increments the counter variable on line 10 and then on line 11 tests to see if counter has gone past 10. If it hasn't, the while loop iterates. If counter is greater than 10, the break on line 12 ends the while loop, and program execution falls through to line 14 where the results are printed.


This program works, but it isn't pretty. This is a good example of using the wrong tool for the job. The same thing can be accomplished by putting the test of counter's value where it belongs—in the while condition.

Infinite loops such as while(1) can cause your computer to hang up if the exit condition is never reached. Use these with caution and test them thoroughly.


C++ gives you many different ways to accomplish the same task. The real trick is picking the right tool for the particular job.

Do
DO use while loops to iterate while a condition is true.
DO exercise caution when using continue and break statements.
DO make sure your loop will eventually end.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.36.174