Contents

Part 1

Chapter 4

If we think about how most of our days go, they start the same with breakfast and going out. Then we have lunch and finish our day. We head home have dinner and relax. Then we go to bed and start the whole process over by getting up the next day. In this simplistic view, every day we have is just a big loop where we repeat the same process over and over. This is the same idea as a loop in our code. Computers are very good at doing very boring tasks that repeat. This idea will allows us to solve the second problem in our sample program from the end of chapter 2.

Iteration

Iteration is the fancy word for looping over a section of code. The loop is the third basic building block in how we will structure our programs. Iteration along with selection will allow us to assemble programs that can process multiple pieces of information and make decisions about what to do with that information.

The while Loop

There are two basic loops in C++ and we will consider the first one here. The most basic and versatile loop is the while loop. The while loop will continue to run until its condition becomes false. This is a distinction from the if statement. The if statement only executes 1 time. The while will continue as many times as needed. Let's look at a basic example of summing the numbers from 1 to 10.

#include <iostream>

using std::cout;
using std::endl;

int main()
{
    int sum = 0;
    int counter = 1;
    while( counter <= 10 )
    {
        sum = sum + counter;
        counter++;
    }
    cout << "The sum of the numbers from 1 to 10 is: " << sum << endl;
    return 0;
}

Program 4.1

So this program shows a few basic ideas that we will need. First, notice how we have to initialize the sum variable. In C++, there is no guarantee as to what the initial value might be. So to ensure that we have a known value we assign it the value 0. Then we have the while statement. It is similar to the if statement in structure but not in how it operates. Then inside of the block that the while is controlling, we have the statements we want to repeat. The first line is what does the sum. It adds the counter to the current value of the sum and then assigns it back to the sum. This is a very common activity. Then we increment the value in the counter using the shortcut notation for adding 1 to a variable. Finally, after the loops end we print the answer.

Another very common task is to continue to process information until there is no more input to process. Our next example will show us an input controlled failure loop.

#include <iostream>

using std::cout;
using std::endl;
using std::cin;

int main()
{
    int sum = 0;
    int counter = 0;
    int number;
    cin >> number; //prime
    while( !cin.fail() ) //test
    {
        sum = sum + number; //process
        counter++;          //process

        cin >> number; //reprime
    }
    cout << "You entered " << counter << " numbers." << endl;
    cout << "The sum of the numbers is: " << sum << endl;
    return 0;
}

Program 4.2

The most important part of this example is the prime, test process, reprime. The prime or priming read, is there to read the first set of data from the input. The test makes sure that the first set of data was read correctly. Then we process. The process is a generic term for do the loop body. The process could be simple like the example or it could be a complex set of tasks. Finally we reprime, or reread the next set of data. This repriming is important to have our loop end correctly. Eventually our input will end, repriming at the end of the loop will cause the test, which will be executed next, to fail and the loop will end correctly. If we only read once, as the first thing we do inside the loop, then the process will be executed an additional time with data that is likely to be incorrect. There are other ways to get this idea to work, but in my opinion this is the cleanest.

This program is very similar to the one in program 4.1 and the one at the end of chapter 2. In this program we have changed our loop from a simple counting loop to one that is checking on the input source and it will continue to loop until the input fails. This is a strange concept to some beginning programmers but it is a very powerful tool. It allows our program to run until it runs out of input. We will learn how we can connect this to a function to allow us to make a very flexible program that can accept input from a variety of sources.

The for Loop

In addition to the while loop there is an alternative loop. The for loop lends itself to tasks that are repeated a certain number of times; however, it may be used any place that a while loop may be used and vice versa. The next example shows the same program as 4.1 but rewritten to use a for loop.

#include <iostream>

using std::cout;
using std::endl;

int main()
{
    int sum = 0;
    int counter;
    for( counter = 1; counter <= 10; counter++ )
    {
        sum = sum + counter;
    }
    cout << "The sum of the numbers from 1 to 10 is: " << sum << endl;
    return 0;
}

Program 4.3

The major difference is how the for loop is filled in. The for loop has the basic syntax

for ( initialization; test; increment )

The initialization section can include a variable declaration like int i = 0; or just an initialization like counter = 1; Notice that the initialization section ends with a semicolon. Then the test section can be any valid boolean expression. It can be a simple expression like counter <= 10; or a complex one that is built up with ands and ors. Then the increment section typically will modify the variable that is being used in the test. Note that the initialization and testing sections both end with a semicolon but the increment section does not.

The "other" Loop

C++ has one last loop, the do-while loop. The do-while loop has a very similar syntax as the while loop but the one major difference is that the do-while loop will always run at least once. The while loop and the for loop may never run. The do-while loop could be used to ask for an input from a user and have it keep asking until they enter an acceptable value. The next sample program demonstrates this.

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main()
{
    int number;
    do
    {
        cout << "Plesae enter an even number." << endl;
        cin >> number;
    }while ( number % 2 != 0 );

    cout << "Thanks, " << number << " sure is even!" << endl;

    return 0;
}

Program 4.4

This simple program demonstrates how the do-while loop works. It enters the do-while loop and asks for a number. Then it reads that number. If the number is even, then the loop is satisfied and ends. If it's not even, then the loop condition is true and it repeats. Once the loop is done, the program prints out the number that was entered. Notice that the while part of the loop ends with a semicolon.

While versus Do-While versus For

The first two loops that we looked at demonstrate what are known as pre-test loops. They are called this because the loop condition is checked before the loop is entered. Both the while and the for loop are pre-test loops and as such might never run. The do-while loop is a post-test and as we saw in program 4.4 will always run at least one time. I recommend using a while loop when you aren't sure which loop to use. It is the most versatile and can be made to work in any situation. It's also a great loop to use when you aren't guaranteed to have any input. The do-while loop will always run once and is a great way to validate user input and make sure it is within a certain range.

Summary

Loops are the third major way we can structure our program and allow us to repeat parts of our code. We didn't show it here, but it is possible to have selection in our loops and even loops in our loops. Using this idea we can build up our program to behave in complex ways using simple building blocks.


Written by: David McPherson © 2019

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

hit counter of smallseotools