EXPLORATION 7

image

For Loops

Explorations 2 and 3 show some simple while loops. This Exploration introduces the while loop’s big brother, the for loop.

Bounded Loops

You’ve already seen while loops that read from the standard input until no more input is available. That is a classic case of an unbounded loop. Unless you know beforehand exactly what the input stream will contain, you cannot determine the loop’s bounds or limits. Sometimes you know in advance how many times the loop must run; that is, you know the bounds of the loop, making it a bounded loop. The for loop is how C++ implements a bounded loop.

Let’s start with a simple example. Listing 7-1 shows a program that prints the first ten non-negative integers.

Listing 7-1.  Using a for Loop to Print Ten Non-Negative Numbers

#include <iostream>
 
int main()
{
  for (int i{0}; i != 10; i = i + 1)
    std::cout << i << ' ';
}

The for loop crams a lot of information in a small space, so take it one step at a time. Inside the parentheses are three parts of the loop, separated by semicolons. What do you think these three pieces mean?

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

The three parts are: initialization, condition, and postiteration. Take a closer look at each part.

Initialization

The first part looks similar to a variable definition. It defines an int variable named i, with an initial value of 0. Some C-inspired languages permit only an initialization expression, not a variable definition. In C++, you have a choice: expression or definition. The advantage of defining the loop control variable as part of the initialization is that you cannot accidentally refer to that variable outside the loop. The disadvantage of defining the loop control variable in the initialization part is that you cannot deliberately refer to that variable outside the loop. Listing 7-2 demonstrates the advantage of limiting the loop control variable.

Listing 7-2.  You Cannot Use the Loop Control Variable Outside the Loop

#include <iostream>
 
int main()
{
  for (int i{0}; i != 10; i = i + 1)
    std::cout << i << ' ';
  std::cout << "i=" << i << ' ';        // error: i is undefined outside the loop
}

Another consequence of limiting the loop control variable is that you may define and use the same variable name in multiple loops, as shown in Listing 7-3.

Listing 7-3.  Using and Reusing a Loop Control Variable Name

#include <iostream>
 
int main()
{
  std::cout << '+';
  for (int i{0}; i != 20; i = i + 1)
    std::cout << '-';
  std::cout << "+ |";
 
  for (int i{0}; i != 3; i = i + 1)
    std::cout << ' ';
  std::cout << "Hello, reader!";
 
  for (int i{0}; i != 3; i = i + 1)
    std::cout << ' ';
  std::cout << "| +";
 
  for (int i{0}; i != 20; i = i + 1)
    std::cout << '-';
  std::cout << "+ ";
}

What does Listing 7-3 produce as output?

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

If you don’t have to perform any initialization, you can leave the initialization part empty, but you still need the semicolon that separates the empty initialization from the condition.

Condition

The middle part follows the same rules as a while loop condition. As you might expect, it controls the loop execution. The loop body executes while the condition is true. If the condition is false, the loop terminates. If the condition is false the first time the loop runs, the loop body never executes (but the initialization part always does).

Sometimes you will see a for loop with a missing condition. That means the condition is always true, so the loop runs without stopping. A better way to write a condition that is always true is to be explicit and use true as the condition. That way, anyone who has to read and maintain your code in the future will understand that you deliberately designed the loop to run forever. Think of it as the equivalent of a comment: “This condition deliberately left blank.”

Postiteration

The last part looks like a statement, even though it lacks the trailing semicolon. In fact, it is not a full statement, but only an expression. The expression is evaluated after the loop body (hence the name postiteration) and before the condition is tested again. You can put anything you want here, or leave it blank. Typically, this part of the for loop controls the iteration, advancing the loop control variable as needed.

How a for Loop Works

The flow of control is as follows:

  1. The initialization part runs exactly once.
  2. The condition is tested. If it is false, the loop terminates, and the program continues with the statement that follows the loop body.
  3. If the condition is true, the loop body executes.
  4. The postiteration part executes.
  5. Control jumps to 2.

Your Turn

Now it’s your turn to write a for loop. Listing 7-4 shows a skeleton of a C++ program. Fill in the missing parts to compute the sum of integersfrom 10 to 20, inclusive.

Listing 7-4.  Compute Sum of Integers from 10 to 20

#include <iostream>
 
int main()
{
  int sum{0};
 
  // Write the loop here.
 
  std::cout << "Sum of 10 to 20 = " << sum << ' ';
}

Before you test your program, you must first determine how you will know whether the program is correct. In other words, what is the sum of the integers from 10 to 20, inclusive? ________________

Okay, now compile and run your program. What answer does your program produce? ________________ Is your program correct? ________________

Compare your program with that shown in Listing 7-5.

Listing 7-5.  Compute Sum of Integers from 10 to 20 (Completed)

#include <iostream>
 
int main()
{
  int sum{0};
  for (int i{10}; i != 21; i = i + 1)
    sum = sum + i;
  std::cout << "Sum of 10 to 20 = " << sum << ' ';
}

A use of for loops is to format and print tables of information. To accomplish this, you need finer control over output formatting than what you have learned so far. That will be the subject of the next Exploration.

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

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