Dave Braunschweig

Counting

// 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 demonstrateWhileLoop(int start, int stop, int increment);
void demonstrateDoLoop(int start, int stop, int increment);
void demonstrateForLoop(int start, int stop, int increment);

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

    demonstrateWhileLoop(start, stop, increment);
    demonstrateDoLoop(start, stop, increment);
    demonstrateForLoop(start, stop, increment);

    return 0;
}

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

void demonstrateWhileLoop(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 demonstrateDoLoop(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 demonstrateForLoop(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

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

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Programming Fundamentals Copyright © 2018 by Dave Braunschweig is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book