Jump to content

Programming Fundamentals/Loop Examples C++

From Wikibooks, open books for an open world

Counting

[edit | edit source]
// This program demonstrates While, Do, and For loop counting using 
// user-designated start, stop, and increment values.
//
// References:
//     https://en.wikibooks.org/wiki/C%2B%2B_Programming

#include 

using namespace std;

int getValue(string name);
void whileLoop(int start, int stop, int increment);
void doLoop(int start, int stop, int increment);
void forLoop(int start, int stop, int increment);

int main() {
    int start = getValue("starting");
    int stop = getValue("ending");
    int increment = getValue("increment");

    whileLoop(start, stop, increment);
    doLoop(start, stop, increment);
    forLoop(start, stop, increment);

    return 0;
}

int getValue(string name) {
    int value;
    
    cout << "Enter " << name << " value:" <> value;
    
    return value;
}

void whileLoop(int start, int stop, int increment) {
    cout << "While loop counting from " << start << " to " << 
        stop << " by " << increment << ":" << endl;
    
    int count = start;
    while (count <= stop) {
        cout << count << endl;
        count = count + increment;
    }
}

void doLoop(int start, int stop, int increment) {
    cout << "Do loop counting from " << start << " to " << 
        stop << " by " << increment << ":" << endl;
    
    int count = start;
    do {
        cout << count << endl;
        count = count + increment;
    } while (count <= stop);
}

void forLoop(int start, int stop, int increment) {
    cout << "For loop counting from " << start << " to " << 
        stop << " by " << increment << ":" << endl;
    
    for (int count = start; count <= stop; count += increment) {
        cout << count << endl;
    }
}

Output

[edit | edit source]
Enter starting value:
1
Enter ending value:
3
Enter increment value:
1
While loop counting from 1 to 3 by 1:
1
2
3
Do loop counting from 1 to 3 by 1:
1
2
3
For loop counting from 1 to 3 by 1:
1
2
3

References

[edit | edit source]