Created
March 21, 2013 00:13
-
-
Save raineorshine/5209682 to your computer and use it in GitHub Desktop.
How to avoid 'break' in your while loop logic (Beginner)
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
| // A | |
| // [get some input from the user and store it in string str] | |
| bool zFound = false; | |
| while(str != "done") | |
| { | |
| if(str.startsWith("Z")) | |
| { | |
| cout << "Z encountered! Terminating!" << endl; | |
| break; | |
| } | |
| doSomething(); | |
| doSomethingElse(); | |
| // get next input from user | |
| } | |
| // B: How is this different from example A? | |
| while(str != "done" && !str.startsWith("Z")) | |
| { | |
| doSomething(); | |
| doSomethingElse(); | |
| // get next input from user | |
| } | |
| // C: Same functionality as A without using a break | |
| while(str != "done" && zFound==false) // what is zFound? | |
| { | |
| doSomething(); | |
| doSomethingElse(); | |
| if(str.startsWith("Z")) | |
| { zFound = true; | |
| cout << "Z encountered! Terminating!" << endl; | |
| // change some variable which will trigger the end of the loop | |
| } | |
| // get next input from user | |
| } | |
| if(zFound) | |
| { | |
| count << "Ended with a Z!" << endl; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment