Programming Fundamentals/Loops/C++

loops.cpp edit

// 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 <iostream>

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:" << endl;
    cin >> 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;
    }
}

Try It edit

Copy and paste the code above into one of the following free online development environments or use your own C++ compiler / interpreter / IDE.

See Also edit