User Tools

Site Tools


cplusplus:repetition_examples

This is an old revision of the document!


Control Structures: Repetition examples

while

simple_while.cpp
// This program counts to an upper limit
#include <iostream>
using namespace std;
 
int main()
{
    const int UPPER_LIMIT = 5;
    int num = 1;
 
    while (num <= UPPER_LIMIT)
    {
        cout << num << endl;
        num = num + 1;
    }
 
    return 0;
}

increment operator

increment-example.cpp
// This program counts to an upper limit
#include <iostream>
using namespace std;
 
int main()
{
    int num = 10;
 
    cout << num << endl;
    num++;
    cout << num << endl;
 
    return 0;
}

Sentinel-controlled repetition

simple-sentinel.cpp
// This program calculates the squares of integers. The user
// enters -999 when finished.
#include <iostream>
using namespace std;
 
int main()
{
    int num = 1;
 
    cout << "Enter an integer and I will tell you its square. " << endl;
    cout << "Enter -999 to quit: ";
    cin >> num;
 
    while (num != -999)
    {
        cout << num <<" squared is " << num * num << "." << endl
             << endl;
        cout << "Enter an integer and I will tell you its square. " << endl;
        cout << "Enter -999 to quit: ";
        cin >> num;
    }
 
    return 0;
}

for

simple-for.cpp
// This program counts to an upper limit
// using a for structure.
#include <iostream>
using namespace std;
 
int main()
{
    const int UPPER_LIMIT = 5;
    int num;
 
    for (num = 1; num <=UPPER_LIMIT; num++)
    {
        cout << num << endl;
    }
 
    return 0;
}

Nested loops

nested-loop.cpp
// This program does some graphics with nested loops.
#include <iostream>
using namespace std;
 
int main()
{
    const int NUM_ROWS = 5;
    const int NUM_COLUMNS = 3;
 
    for (int row = 1; row <= NUM_ROWS; row++)
    {
        for (int column = 1; column <= NUM_COLUMNS; column++)
        {
            cout << "*";
        }
        cout << endl;
    }
    return 0;
}

break and continue

simple-break.cpp
// Print out a list of powers of 2.
#include <iostream>
#include <cmath>
using namespace std;
 
int main()
{
    const int UPPER_LIMIT = 100;
    int num = 1;    // counter
    char choice;    // used to get user input
 
    while (num <= UPPER_LIMIT)
    {
        cout << "2 to the " << num << " power is " << pow(2, num) << endl;
        cout << "Should I go on? [y/N]: ";
        cin >> choice;
        if (choice == 'N' || choice == 'n')
            break;    // (try replacing with continue)
        num++;
    }
 
    cout << "Goodbye!" << endl;
    return 0;
}
cplusplus/repetition_examples.1362100213.txt.gz · Last modified: 2013/03/01 01:10 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki