Skip to Main Content
Practical C++ Programming, 2nd Edition
book

Practical C++ Programming, 2nd Edition

by Steve Oualline
December 2002
Beginner to intermediate content levelBeginner to intermediate
576 pages
14h 6m
English
O'Reilly Media, Inc.
Content preview from Practical C++ Programming, 2nd Edition

Chapter 8. More Control Statements

Grammar, which knows how to control even kings . . .

Molière

At this point we know enough to create very simple programs. In this chapter we move on to more complex statements. For controlled looping we have the for statement. We also study the switch statement. This statement can be quite powerful and complex, but as we shall see in the following sections, if used right it can be very efficient and effective.

But we start our discussion with a new looping statement, the for.

for Statement

The for statement allows you to execute a block of code a specified number of times. The general form of the for statement is:

for (initial-statement; condition; iteration-statement)
    body-statement;

This is equivalent to:

               initial-statement; 
while (condition) { 
    body-statement; 
    iteration-statement;
}

For example, Example 8-1 uses a while loop to add five numbers.

Example 8-1. total6/total6w.cpp

#include <iostream>

int total;      // total of all the numbers 
int current;    // current value from the user 
int counter;    // while loop counter 

int main(  ) {
    total = 0;

    counter = 0;
    while (counter < 5) {
        std::cout << "Number? ";

        std::cin >> current;
        total += current;

        ++counter;
    }
    std::cout << "The grand total is " << total << '\n';
    return (0);
}

The same program can be rewritten using a for statement, as seen in Example 8-2.

Example 8-2. total6/total6.cpp

#include <iostream> int total; // total of all the numbers int current; // current value from the user int counter; // for loop counter ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Discovering Modern C++, 2nd Edition

Discovering Modern C++, 2nd Edition

Peter Gottschling

Publisher Resources

ISBN: 0596004192Supplemental ContentErrata Page