Created
October 1, 2013 18:58
-
-
Save natemcmaster/6783327 to your computer and use it in GitHub Desktop.
Tutoring: demo of using loops to get user input from cin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int main() | |
{ | |
double miles; | |
cout << "Enter miles:" << endl; | |
cin >> miles; | |
cout << 100 / miles << endl; | |
// Problem: In the code above, the user might give us a bad number (e.g. 0 or -100) that produces bad results. | |
// How can we prevent this? | |
// Answer: looping. | |
// There are three types of loops in C++. | |
// For loop - This loop will execute five times. This is not useful (for this problem): how can we be sure the 5th time is the right number? | |
for(int i=0; i < 5; i++) | |
{ | |
cout<<"Enter miles:" << endl; | |
cin >> miles; | |
} | |
cout << 100 / miles << endl; | |
// While loop - this will execute until the user gives a correct input. | |
cout<<"Enter miles:" << endl; | |
cin >> miles; | |
while(miles <= 0) | |
{ | |
cout<<"Miles must be greater than zero."<<endl; | |
cout<<"Enter miles:"<<endl; | |
cin >> miles; | |
} | |
cout << 100 / miles << endl; | |
// Do-While loop - notice how the the While-loop example above, we had to repeat the same code twice to make it work. | |
// The Do-While loop is useful when you always need to run a piece of code at least once, maybe more. | |
do{ | |
cout << "Enter miles:" << endl; | |
cin >> miles; | |
if (miles < 0) | |
cout << "Miles must be > 0." << endl; | |
} while (miles < 0); | |
cout << 100 / miles << endl; | |
system("pause"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment