Previous Page TOC Next Page



- 11 -
What while Is for


for loops


What You'll Learn About


Computers do a lot of things that people find boring. They add and subtract. They print reams of information. They wait patiently while a user sits at the keyboard trying to find the Enter key. Computers do all these things without complaint as long as their programs contain no syntax errors (which, of course, none of your programs will!).

Not only do computers do all these things, but they do them very fast. Extremely fast. Their speed gives computers the added advantage of being able to perform multiple repetitions of the same tasks.

definition

A loop is a program's repeated execution of the same set of instructions.

When your programs contain loops, they can repeat the same set of code a lot. The computer can repeat the code hundreds, even thousands, of times. Computers repeat so rapidly that the user usually notices no delay at all. Suppose you wrote a program that calculated payroll figures. Instead of running the same program over and over for each employee, the user would have to run the program only once. A loop within the program would keep calculating each employee's data until the entire payroll was finished.

Looping is a very important concept in programming. It is so important that Visual C++ provides three different forms of loops to repeat statements over and over: while and do...while loops, which do things over and over until some condition is true, and the for loop, which performs some actions a specific number of times.

The Format of while




The while loop repeats as long as a relational test is true. As soon as the relational test becomes false, the while loop terminates and the rest of the program continues.

In programming, there will be times when you want to do the same task over and over again. For example, you might want to write a quiz program and ask the user the same question until he or she gives the right answer. You could write the same code over and over again, but often you want to do things hundreds or thousands of times—in which case your programs would get very long! Instead, you can use a loop. You decide what code you want to use repeatedly, and place it inside a loop. Inside the loop, you might ask a question and get new input over and over again or use other advanced techniques such as arrays to access different data each time around the loop. Each time around the loop, C++ can ask the question, "Should I do the loop again?" In the while loop, C++ asks the question before each time it starts executing the loop.

The while loop requires the while statement. while is a command, just as return, if, and else are commands.



while isn't a library function. Therefore, it doesn't use any header files.

definition

An infinite loop never stops executing.

When you want your program to execute the same series of statements over and over, one of the most important points to plan is when the loop should terminate. No matter how fast your computer is, if you write a program that contains a loop that loops without stopping, the endless infinite loop hangs up and the program never lets the user stop the program or return to Visual C++.

To keep loops from executing forever, you write a controlling relational test, just like the relational tests that appear inside if statements. The loop repeats as long as the relational test is true. Unlike an if statement, a while body keeps repeating as long as the while's relational test is true. The if statement's body executes only once if the if's relational test is true.

You must make sure that something inside the loop eventually changes the while's relational test. If the relation is true when the while first begins, and if nothing inside the body of the while ever changes the relational test, it executes forever. The loop will never stop, and you'll lose your title of "Master C++ Guru Programmer."



If you accidentally write a QuickWin program that contains an infinite loop, you can terminate the program by pressing Ctrl+Break or Ctrl+C. Visual C++ then stops the program and returns to the QuickWin window.

We're a few pages into this unit and you've yet to see a while loop. Enough introduction. Here's the format of the while loop:


while (relationalExpression)

  {

     // Block of one or more Visual C++ statements

  }

Just like if, while is a multiline statement. Also like if, parentheses must appear around the relational expression. The relational expression can contain one or more relational operators. If you use more than one relational operator inside the relational expression, use logical operators (&& and ||) to combine the relational tests.



Indent the body of the while loop so that when you maintain the program, you'll be able to spot where the loop's code begins and ends.

The body of the while loop doesn't require braces if it has only one statement. However, you should get in the habit of using the braces so that you won't forget them later if you add more statements to the while loop.

Don't put a semicolon after the relational test's closing parenthesis. The while loop would then be an infinite loop, because Visual C++ would think that the body of the loop was a null statement (empty), and null statements can't change the loop's controlling relational test.

The relational test appears at the top of the while loop. The location of the test is important; if the while expression is false the first time through, the loop will not execute even once! The body of the while loop executes only if the relational expression is true, and it keeps executing as long as the relational expression is true. If and when the relational expression becomes false, the program continues at the statement following the while loop's closing brace.

Figure 11.1 illustrates the while loop's action. while is somewhat like a repeating if test. If the relational expression is true, the while body repeats its execution. If the relational expression is false, the while body stops executing and the program continues from there.

Figure 11.1. The body of the while executes as long as the relational expression is true.

The following while loop prints Happy Birthday! on-screen 10 times. Notice that instead of using 10 separate couts, you need to specify only one inside a while loop that loops 10 times:


int count = 0;

while (count < 10)

  {

    cout << "Happy Birthday!" << endl;

    count++;   // VERY important!

  }

Why is it important to increment the count variable? If you don't increment count, the loop will be infinite! Remember that the body of the loop should always change something in the while's relational test so that the relational test eventually becomes false and the loop can stop.



Counters

The count variable in the preceding while loop is called a counter variable. Each time through the loop, the program increments count. Just as when you count 0, 1, 2, 3, and so on, count starts out holding a 0, and then 1, 2, 3, and so on, until Visual C++ increments count to the final value of 10. At this time, the relational test becomes false and the loop terminates.


Listing 11.1 contains a program that asks the user for an age. If the user enters an age less than 5 or more than 110, the program doesn't believe the user and asks again. Until now, if the user entered a bad value, the program stopped early. Now, you can keep asking the user until he or she enters a value within an expected range.



The while loop lets you repeat sections of your program as long as the relational test is true.

Input Listing 11.1. Using while to verify user input.

  1:// Filename: USERAGE.CPP

  2:// Uses a while loop to get an age from the user

  3:#include <iostream.h>

  4:void main()

  5: {

  6:   int age;

  7:

  8:   cout << "How old are you? ";

  9:   cin >> age;

 10:

 11:   while ((age < 5) || (age > 110))

 12:     {

 13:       cout << "I'm not sure that I believe you are "

 14:            << age << endl;

 15:       cout << "Try again..." << endl << endl;

 16:       cout << "How old are you? ";   // Get the age again

 17:       cin >> age;

 18:     }

 19:   // The program continues if the user entered a reasonable age

 20:   if (age < 16)

 21:     {

 22:       cout << "Your curfew is at 11:30 pm" << endl;

 23:       cout << "Have fun!"  << endl;

 24:     }

 25:   else

 26:     {

 27:       cout << "You're old enough to drive, so be careful ";

 28:       cout << "out there!" << endl;

 29:     }

 30:   return;

 31: }

Output


How old are you? -32

I'm not sure that I believe you are -32

Try again...

How old are you? 192

I'm not sure that I believe you are 192

Try again...

How old are you? 25

You're old enough to drive, so be careful out there!

Analysis

The user's entered age determines what the program does. First of all, if the user enters an age that isn't within the range between 5 and 110, the program prints an error message in lines 13 and 15. Actually, the program prints a warning, not an error, because as soon as the user enters a bad age, the program asks the user for another age and tests the age all over again via the loop in lines 11 through 18. The while will continue looping as long as the user's value isn't within the expected range.

The rest of the program primarily consists of an if-else in lines 19 through 27 that prints one message or another, depending on the user's age. Unlike the while, the if never repeats its body more than once. When the if body finishes, the program always continues on to the return, where it then returns to QuickWin and finishes.



This program contains two sets of duplicate lines: Lines 8 and 9 are repeated in lines 15 and 16. After mastering the second kind of while loop discussed in the next section (there are two), you'll see a way to eliminate the duplication of lines of code.


The Other while: The do-while Loop




There is a second while loop, called the do-while loop, whose relational test appears at the bottom of the loop's body instead of at the top.

Visual C++ contains two while loops: the while loop that you read about in the preceding section and the do-while loop. Although these loops are similar, they differ in where they test their relation. Here is the format of do-while:


do

  {

    // Block of one or more Visual C++ statements

  }

while (relationalExpression);

As with the while loop, the braces around the body aren't required if it contains a single statement. However, you should use the braces in all cases for clarity and future maintenance. You must put parentheses around the relational expression. The final semicolon after the relational test is required to terminate the do-while statement.

You should use a do-while loop instead of a while loop when you want the body of the loop to execute at least once. The location of the do-while's relational test causes execution to fall through and execute the body of the loop at least once. Only after the body executes once can the do loop check the relational test to see whether the loop should loop again or terminate. Only after the relational test is false will the rest of the program continue executing.

definition

An iteration is one cycle through the body of a loop.



The while loop might never execute because Visual C++ checks the relational test before the body has a chance to execute. do-while doesn't test the relation until the loop executes one full iteration. Figure 11.2 shows how the do loop works as opposed to how while works (which you saw in Figure 11.1).

Figure 11.2. The body of a do-while always executes at least once.

Here is a do-while that prints Happy Birthday 10 times:


int count = 0;

do

{ cout << "Happy Birthday!" << endl;

count++;

} while (count < 10);

Listing 11.1 asked the user for his or her age and printed an appropriate message. Listing 11.2 improves upon that program by using a do-while loop. The use of do-while as opposed to while means that you don't have to repeat the age prompt and the user's cin. However, an extra if is needed to capture any mistake the user makes.



do-while ensures that the body of the loop executes at least once.

Input Listing 11.2. Keep asking for a correct age if needed with do.

  1:// Filename: DOUSRAGE.CPP

  2:// Uses a do-while loop to get an age from the user

  3:#include <iostream.h>

  4:void main()

  5:{

  6:  int age;

  7:

  8:  // In the previous listing, two extra lines went here

  9:  do

 10:    { cout << "How old are you? ";   // Get the age

 11:      cin >> age;

 12:      if ((age < 5) || (age > 110))

 13:        { cout << "I'm not sure that I believe you are "

 14:               << age << endl;

 15:          cout << "Try again..." << endl << endl; }

 16:    } while ((age < 5) || (age > 110));   // Quit after good input

 17:

 18:  // The program continues if the user entered a reasonable age

 19:  if (age < 16)

 20:    { cout << "Your curfew is at 11:30 pm" << endl;

 21:      cout << "Have fun!" << endl;

 22:    }

 23:  else

 24:    {

 25:      cout << "You're old enough to drive, so be careful ";

 26:      cout << "out there!" << endl;

 27:    }

 28:  return;

 29:}

Output


How old are you? 2

I'm not sure that I believe you are 2

Try again...

How old are you? 3224

I'm not sure that I believe you are 3224

Try again...

How old are you? 12

Your curfew is at 11:30 pm

Have fun!

Analysis

The use of do-while keeps the program from repeating these lines, as was done in Listing 11.1:


cout << "How old are you? ";   // Get the age again

cin >> age;

The use of do-while requires an extra if statement that Listing 11.1 didn't need. The if in line 12 ensures that the age warning message prints only if the user enters an age outside the range. Whether to use while without the extra if or do-while with the extra if is up to you.

The for Loop's Structure




Learn the format of the for statement. A single for statement requires three values that control the loop.

The for statement makes for loops look rather difficult, but as you'll see, for loops aren't hard to understand. Visual C++'s syntax requirements for the for statement are a little strange looking, but Visual C++ has never been known for being a verbose language. Here is the format of the for loop:


for (startExpression; conditional; countExpression)

  {

  // Block of one or more Visual C++ statements

  }

When Visual C++ encounters a for statement, it follows these steps to perform a loop:

  1. Perform the startExpression, which is usually just an assignment statement.

  2. Test the conditional expression for a true or false result.

  3. Perform the body of the loop if the conditional is true.

  4. Perform the countExpression, which usually is an increment or decrement operation.

  5. Go back to step 2.

When the conditional is tested and found to be false, Visual C++ stops looping and the program continues at the statement following the for loop. As with while, never put a semicolon right after the for statement's parentheses. However, semicolons are required inside the parentheses. Until now, you've never seen semicolons inside a statement. The for loop is the only statement that requires such semicolon placement.

If the body of the for statement contains a single statement, the braces aren't required. But, as with the while loops, braces are recommended even when the body contains only a single statement.



You'll see that the semicolons inside the for statement aren't all that strange. Semicolons always terminate executable statements, and the startExpression and the conditional are individual statements inside for. The for's two semicolons help separate the three statements inside the parentheses.

definition

A control variable is a variable controlled and changed automatically by the for loop.

After reading through the action of for loops, you might feel as if they're just complicated while loops that are controlled by a conditional statement just as the while loops are. The for loop, however, is slightly different from either of the while loops, not only in its syntax but also in the way that it updates its important loop control variable for you.



Can you see that indenting the body of the for loop, as you did with the while loops, makes the body of the loop stand out? You can tell at a glance where the loop body begins and ends.

Here is a sample for loop:


for (i = 1; i <= 10; i++)

  {

    cout << i << endl;

  }

When Visual C++ gets to this for loop, it writes the following output to the screen:


1

2

3

4

5

6

7

8

9

10

Visual C++ automatically updates the integer i each time the for loop executes. The body of this for loop executes exactly 10 times, hence the 10 lines in the output. Here are the parts of this for loop:

countExpression: i++

Next are the five actions of the for loop applied to this specific loop. Follow the actions listed here and you'll see how Visual C++ produced the numbers from 1 to 10:

  1. Assigns 1 to the variable i. This two-line for loop assumes that you've already defined an integer variable named i. Visual C++ executes this startExpression only once before the loop begins.

  2. Visual C++ tests the conditional, i <= 10, to see whether it's true or false. The first time Visual C++ enters the loop, i is 1 (due to the assignment just made in step 1) and the conditional is true, so Visual C++ executes the body of the loop.

  3. The statement inside the loop body executes, the first time printing a 1 for i.

  4. The countExpression executes, adding 1 to i, so that it stores a 2 in i.

  5. Visual C++ goes back to step 2, testing the conditional again and executing the body of the loop nine more times until i contains 11. At that point, Visual C++ terminates the loop and the program continues.

Here is an equivalent while loop:


i = 1;

while (i <= 10)

  {

    cout << i << endl;

    i++;

  }

The while doesn't really require less typing than the equivalent for. The increment of i resides in the body of the while instead of in the loop's first statement as it does in the for. Also, the initial value of i must be set before Visual C++ ever begins the while loop, whereas the first line of the for initializes i to its first value.

The biggest difference between while and for is that you can tell at a glance, in a single statement, how Visual C++ controls for, whereas you must do more searching to find the controlling values of a while loop.



The for loop is not a good loop to use for input validation, but the while loops are good for this purpose, as you discovered in the previous unit. for is better when you know in advance exactly how many times you want a loop to execute. In the previous for loop, the body of the loop executed exactly 10 times, with the expressions inside the for statement controlling the 10 executions.

Figure 11.3 helps show the action of the for loop. The line traces the loop's execution path. Notice that the startExpression executes only once. Also, the loop's test is at the top, similar to a while loop's (but not a do-while loop, which tests at the bottom of the loop), meaning that there is a chance that the body of the for loop might never execute.

Figure 11.3. The execution path of a for loop.

If the conditional is false to begin with, as the following for statement's is, the body of the loop never executes:


for (i = 15; i <= 10; i++)   // The conditional is false from the start

  {

    cout << "This cout never executes!!";

  }

When this loop first begins, Visual C++ stores a 15 in i. The conditional test, i <= 10, is false, so Visual C++ terminates the loop and continues the program right after the loop without ever executing the body of the loop.



Visual C++ lets you define variables right before you use them for the first time. Therefore, if you need a control variable for only one for loop, you might consider defining that variable inside the for statement as done here:

Listing 11.3 contains a program that asks the user for five values, averages those values, and prints the average. A for loop ensures that the user is asked for the five values.



The for loop initializes and increments control variables for you so that you can execute a loop a specific number of times.

Input Listing 11.3. Using a for loop to compute the user's average.

  1:// Filename: FORAVG.CPP

  2:// A for loop asks the user for five values.

  3:// As the user enters each value, a compound

  4:// assignment statement adds the values.

  5:// After all five values have been entered and

  6:// the loop ends, the program prints an average.

  7:#include <iostream.h>

  8:

  9:void main()

 10: {

 11:   float value, avg;

 12:   float total = 0;

 13:

 14:   cout << endl << "** An Average Program **"

 15:        << endl << endl;

 16:

 17:   // Loop five times

 18:   for (int count = 0; count < 5; count++)

 19:     {

 20:       cout << "What is the next value? ";

 21:       cin >> value;

 22:       total += value;   // Add to the total variable

 23:     }

 24:

 25:   // Now, compute and print the average

 26:   avg = total / 5.0F;

 27:   cout.precision(1);

 28:   cout.setf(ios::fixed);

 29:   cout.setf(ios::showpoint);

 30:   cout << endl << "The average of your values is "

 31:        << avg << endl;

 32:   return;

 33: }

OUTPUT


** An Average Program **

What is the next value? 34.5

What is the next value? 65.4

What is the next value? 78.9

What is the next value? 76.5

What is the next value? 43.2

The average of your values is 59.7

ANALYSIS

The for loop on line 18 is similar to many that you'll see. This loop iterates exactly five times, as controlled by the loop's control variable, count. count begins at 0, and then continues incrementing each time through the loop until its value reaches 5. The conditional statement, count < 5, is then false and the loop terminates. Execution of the program then continues at line 24.

What if you wanted to average more than five values? You would have to change only two statements. You would have to change line 18's conditional statement to test for a value other than 5 and change the average calculation on line 26 because you could no longer divide by 5.



To make the program even easier to change and update, change line 26 to this:

avg = total / count;

To change the number of average values now, you only need to change the loop's conditional test. When line 19's for loop finishes, count always holds the number of values that the user entered. To make the program even more maintainable, don't even conditionally test against a numeric literal on line 19. Instead, define a constant variable at the top of the program as done here:

const int NUMBER = 5;

Then make the for loop's conditional statement compare against the named constant:



for (count = 0; count < NUMBER; count++)

After you change the program as suggested here, you'll need to change only one line, the const, to make the program work with a different number of values.


Further Control with countExpression




for loops don't have to increment. You can decrement the loop control variable as well as update the control variable with a value different from 1.

The third part of the for statement, the countExpression in parentheses, doesn't always have to increment the control variable. Inside the countExpression, you can decrement or update the control variable by any value your application requires. Consider the following for loop:


for (i = 10; i >= 1; i--)

  {

    cout << i << endl;

  }

cout << "Blast off!" << endl;

Notice that the control variable i begins at 10, not 0 or 1 as has been the case previously. The conditional statement stays true as long as i remains greater than or equal to 1. The countExpression decrements i. Here is the output from this loop and the subsequent cout:


10

9

8

7

6

5

4

3

2

1

Blast off!

You must be sure to initialize the control variables properly. The for loop is a compact way to initialize, test, and control a loop in a single statement.

One interesting thing to note is that the for loop's parentheses don't have to hold all three expressions. For example, instead of


for (num = 2; num <= 40; num += 2)

you can do this:


num = 2;

for ( ; num <= 40; )

  {   // Body of loop goes here

    num += 2;   // Increment the control variable in the loop

  }

Taking the expressions out of the for statement is sometimes warranted, especially when the user initializes the control variable's starting value with cin instead of your program initializing the value with an assignment statement. Nevertheless, for most uses of for loops, place all three expressions inside the for parentheses so that all control information is available at a glance in one statement.

Homework



General Knowledge


  1. What is a loop?

  2. What's the difference between a loop and an infinite loop?

  3. If your program enters an infinite loop, how can you stop the execution?

  4. Why should you never put a semicolon at the end of the while loop's parentheses?

  5. Why is it recommended that you put braces around the while and do-while loop bodies?

  6. Which is better for looping a specific number of times: a while loop, a for loop, or a do-while loop?

  7. How does a for loop differ from a while loop?

  8. How does the format of a for loop help you spot the entire control of the loop in a single statement?

  9. When are braces required around a for loop's body?

  10. What happens when the conditional expression in a for loop becomes false?

  11. True or false: The body of a do-while loop might never execute.

  12. True or false: A for loop's body might never execute.

  13. True or false: The semicolons inside the for loop are optional.

  14. True or false: Visual C++ tests the for's condition before the first iteration of the loop.


    What's the Output?


  15. How many times do the letters abc print in the following code?

    
    int c = 1;
    
    while (c < 20)
    
      { cout << "abc" << endl;
    
        c++;
    
      }

  16. How many times do the letters abc print in the following code?

    
    int c = 0;
    
    while (c <= 20)
    
      { cout << "abc" << endl;
    
        c++;
    
      }

  17. What's the output of the following section of code?

    
    for (c = 0; c <= 10; c += 3)
    
      { cout << c; }

  18. What's the output of the following for loop? Will an error occur?

    
    for (i = 5; i; i--)
    
      {
    
        cout << i << " "  << endl;
    
      }

    Find the Bug


  19. Can you find anything wrong with the following loop?

    
    a = 10; b = 4;
    
    while (a >= 10)
    
      { cout << "a is now " << a << endl;
    
        b += 2;
    
        cout << "b is now " << b << endl;
    
      }

  20. Carl the Visual C++ coder wants to print a special warning message 10 times if his company's costs get too high. Carl coded the following, but the results aren't working exactly as he expected:

    
    if (costs >= 25000.00)
    
      {  count = 0;
    
         while (count < 10)
    
           cout << "** Please lower costs immediately **"
    
                << endl;
    
           count++;
    
      }

  21. Help Carl fix the problem.

    Write Code That. . .


  22. Write a program that defines a character array 80 bytes long. Ask the user for his or her first name (80 bytes is more than enough to hold anyone's response). Using an integer variable and a while loop, find the length of the user's name (the string's length). Hint: Add one to the integer variable each time through the loop and stop when you get to the terminator ('\0'). Note: The string length variable is a counter variable.

  23. Use a for loop to print the letters of the alphabet in uppercase. To do this, use a character variable, initialize it (within the for) with 'A', and increment it using ++. Although applying ++ to a character variable might seem wrong, remember that because Visual C++ maintains a close relationship between character variables and integer variables, you can interchange simple operations between them.

    Extra Credit


  24. Write a number-guessing game. Store an integer in a variable. Ask the user to guess the number between 1 and 100. If he guesses the variable's value, congratulate him. If he doesn't guess the value, give him a clue (higher or lower) and ask again. If the guess is 0, stop the program. (Hint: the checking will have to check two conditions, whether the guess was 0, or whether the guess was correct).

Previous Page Page Top TOC Next Page