Iteration

Control Structures - C++ has three types of control structures

  1. sequence structures - built into C++; unless directed otherwise, computer executes each and every C++ statement one after another, top to bottom
  2. selection structures - used to chose among alternative courses of action
  3. iteration structures - allow a set of instructions to be repeated until a certain condition is reached; a condition may be open-ended as in a "while" and "do/while" loops or it may be predefined as in the "for" loop

Iteration Structures (types of loops)

Counter-Controlled Loops
A counter-controlled iteration structure is used when you know (or when the program can calculate in advance) the number of times a statement block should execute; the "while" loop continues to execute as long as the condition (expression) is true

while (condition)
    statement;

to include several statements in the body of a while (instead of one statement as shown previously), you include the statements in braces, { and } This is called a compound statement

want to execute statement 10 times

i=1;
while (i <= 10)
{
    statement;
    i++;
}

Lab 6 Core 1 background & warmup(show debugger), HTML overview for application exercise

Loop Example (work through on board or on PC)

Event-Controlled Loops
An event-controlled loop (while loop), executes as long as the test expression is satisfied (true). Don't have to know how many times loop will be executed beforehand.

while (condition)
    statement;

Lab 6 Core 2 background & warmup, pseudo-code for application exercise

Examples of event-controlled loops
// take in numbers between 0 and 9 and double them
#include <iostream.h>
int main()
{
    int number;
    cout << "Enter a number between 0 and 9 inclusive:";
    cin >> number;

    while (number>=0 && number <=9)
    {
        cout << "Double " << number << " is " << number*2 << "\n";
        cout << "Enter a number between 0 and 9 inclusive:";
        cin >> number;
    }
    cout << number << " is not between 0 and 9.\n";

    return 0;
}

example: want to get valid input ranging from 1 to 10 (integer) keep asking user until valid input is given
//Get integer value between 1 and 10
#include <iostream.h>
int main ()
{
    float value = -99; //initialize value

    while (!(value = = int(value) && (value > 0) && (value < 11)))
    {
        cout << endl << "Enter an integer value between 1 and 10 ";
        cin >> value;

        cout << endl << "The value entered is " << value;
    }

    return 0;
}
e.g. enter 7.3 => stay in loop (1st condition fails) 11 => stay in loop (3rd condition fails)

Combined Counter/Event-Controlled Loops - See Lab 6 Core 3 background & warmup

Counter-Controlled "for" Loops
The "for" structure is an alternate counter-controlled loop structure when you know (or when the program can calculate in advance) the number of times a statement block should execute; the "for" loop continues to execute as long as the condition (test expression) is true

for (initialization expression; test expression; increment expression)
    statement;

What do we need to specify?

// want to execute statement 10 times
for (i =1; i <= 10; i++)
    statement;

-or

for (k = 10; k > 0; k--)
    statement;

// average 10 numbers using a for loop for input
#include <iostream.h>
int main()
{
    int number, i, sum=0;
    float average;

    for (i=0; i<10; i++)
    {
        cout << "Enter a number: ";
        cin >> number;
        sum = sum + number;
    }
    average = sum / 10.;
    cout << "The average of the 10 numbers is "<<average" << "\n";

   return 0;
}

See Lab 6 Core 4 background & warmup

Examples of counter-controlled "for" loops
// Displays table of the first five positive integers and their cubes using for loop.
#include <iostream.h>      // for cin and cout
#include <iomanip.h>       // for setw()
#include <math.h>           // for pow(x,y) function, raises x to y power

int main()
{
    const int MAX_NUM = 5;
    int num;

    cout << endl << "Number" << " Cube" << endl;

    // Execute the loop while num does not exceed MAX_NUM.
    for ( num = 1; num <= MAX_NUM; num++ )
        cout << setw(6) << num << setw(6) << pow(num,3) << endl;

   return 0;
}

// Displays table of the first five odd positive integers and their cubes using for loop.
#include <iostream.h>      // for cin and cout
#include <iomanip.h>       // for setw()
#include <math.h>           // for pow(x,y) function, raises x to y power

int main()
{
    const int MAX_NUM = 10;
    int num;

    cout << endl << "Number" << " Cube" << endl;

    // Execute the loop while num does not exceed MAX_NUM.
    for ( num = 1; num <= MAX_NUM; num += 2 )
        cout << setw(6) << num << setw(6) << pow(num,3) << endl;

    return 0;
}

// Displays table of the first five positive integers (in descending order) and their cubes using for loop.
#include <iostream.h>      // for cin and cout
#include <iomanip.h>       // for setw()
#include <math.h>           // for pow(x,y) function, raises x to y power

int main()
{
    const int MAX_NUM = 5;
    int num;

    cout << endl << "Number" << " Cube" << endl;

    // Execute the loop while num is positive.
    for ( num = MAX_NUM; num >= 1; num-- )
        cout << setw(6) << num << setw(6) << pow(num,3) << endl;

    return 0;
}

Sentinel Event-Controlled Loops
Sentinel value triggers loop termintation
// Averages an input set of numbers.
#include <iostream.h>
#include <iomanip.h>
int main ()
{
    int num, // Input value
    count = 0; // Number of input values
    double sum = 0.0; // Sum of input values

    cout << endl << "Enter a set of numbers (-1 to stop): " << endl;
    cin >> num;

    while ( num != -1 )
    {
        count++;  // count = count + 1;
        sum += num; // sum = sum + num;
        cin >> num;
    }
    cout << "Average is " << sum/count << endl;

    return 0;
}

Lab 6 Reinforcement pseudo-code

Discuss infinite loops, loops that never execute, and "off-by-one" errors Lab 6 Analysis

I/O Loops
See Lab 7 Core 1 background & warmup, show debugger, pseudo-code for application exercise

Nested Loops
See Lab 7 Core 2 background & warmup, discuss HTML <table> tags, pseudo-code for application exercise

"do/while" Loops
The "do/while" structure is similar to the "while" structure(pre-test) except that it evaluates its condition after the loop statement(s) are executed(post-test); a "do/while" structure always executes its statements at least once.

    do
        statement;
    while (condition)

// count from 1 to10
#include <iostream.h>
int main()
{
    int counter;
    counter=0;

    do
    {
        counter++;
        cout << counter << "  ";
    }
    while (counter < 10);

    return 0;
}

// Sample program using do..while and switch statements
#include <iostream.h>

int main ()
{
    int aCount = 0, bCount = 0, cCount = 0;
    char letterGrade;

    cout << endl << "Enter the letter grades ('Q' to quit): " << endl;

    do
    {
        cin >> letterGrade;

        // Execute the selected test.
        switch ( letterGrade )
        {
            case 'A': case 'a': cout << "1st case" << endl; aCount++; break;
            case 'B': case 'b': cout << "2nd case" << endl; bCount++; break;
            case 'C': case 'c': cout << "3rd case" << endl; cCount++; break;
            case 'Q' : case 'q': break;
            default : cout << "Invalid input" << endl;
        }
    } while ( letterGrade != 'Q' && letterGrade != 'q');

    cout << "Totals:" << endl
           << "A: " << aCount << endl
           << "B: " << bCount << endl
           << "C: " << cCount << endl;

    return 0;
}

Lab 7 Core 3 background & warmup

Copyright Matthew Bauer, Computer Science, Illinois Institute of Technology, Fall 2000