Skip to content

Instantly share code, notes, and snippets.

@natecraddock
Last active February 17, 2021 03:19
Show Gist options
  • Save natecraddock/f28ccd063c993801ab99eb817e4aa2c6 to your computer and use it in GitHub Desktop.
Save natecraddock/f28ccd063c993801ab99eb817e4aa2c6 to your computer and use it in GitHub Desktop.
Examples of while, for, and do-while loops in c++ for CS 142
#include <iostream>
#include <string>
#include <limits> // For numeric_limits<streamsize>::max()
using namespace std;
int main() {
int number;
string name;
// This first example checks cin.fail() to see if the input was not
// able to be stored in an integer variable.
cout << "Enter a number: ";
cin >> number;
while (cin.fail()) {
cout << "Invalid input!" << endl;
cin.clear();
// Ignore all charracters until the next line ('\n')
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// Ask again!
cin >> number;
}
// This loop could validate ranges in inputs (make sure the number is within a range)
cin >> number;
while (number < 0) {
cout << "Invalid input!" << endl;
cin >> number;
}
// This can check for specific allowed inputs
char option;
cin >> option;
while (option != 'n' && option != 'y') {
cout << "Invalid input!" << endl;
cin >> option;
}
cout << "Enter your name: ";
cin >> name;
// All 4 following loops are equivalent
int numberOfLoops = 0;
while (numberOfLoops < number) {
cout << "Hello " << name << "!" << endl;
numberOfLoops += 1;
}
numberOfLoops = 0;
do {
cout << "Hello " << name << "!" << endl;
numberOfLoops += 1;
} while (numberOfLoops < number);
for (int i = 0; i < number; i += 1) {
cout << "Hello " << name << "!" << endl;
}
numberOfLoops = 0;
for (; numberOfLoops < number; ) {
cout << "Hello " << name << "!" << endl;
numberOfLoops += 1;
}
// Note that the for loop's counter variable (i) is only available
// within the loop. Trying to output i outside the loop would fail
// cout << i; <- THIS FAILS!
// Sometimes it is better to keep the variable outside the loop
// (like in the case of numberOfLoops) but most often it is fine to
// leave it in the initializer part of the for loop.
// One last example of an equivalent loop
while (number > 0) {
cout << "Hello " << name << "!" << endl;
number--;
}
// This example actually modifies "number" which might
// not be what you expect! If you need that variable later then
// you no longer have the original value after the loop.
// In some programs though this is perfectly fine.
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment