Professional Documents
Culture Documents
Repetition
Repetition
Statement1
Condition
True
False
Set 2 of Statements
Set 1 of Statements
statement2 is called the body of the while loop the variables appearing in the condition are called the loop control variables (lcv) The lvcs control the number of iterations of the loop in order for the loop to terminate, the lcvs should be updated inside the loop body
// lcvs are initialized before the loop while (condition) statement2 statement3 // lcvs are used in the condition // lcvs are updated in the body
char ch; cin.get(ch); if (ch >= a && ch <= z) ch = ch 32; cout << ch << endl;
I want to repeat it 10 times repeat what?
while (count < 10) { cin.get(ch); if (ch >= a && ch <= z) ch = ch 32; cout << ch << endl;
count = count + 1; // usually the last statement }
Keep initializecontrolnumberlcv iterarations a test conditionvariable? Loop control mechanism? update of the in the body count the lcv using of Loop lcv before the loop
Counter-controlled
The number of iterations are given
char ch; int count; count = 0; while (count < 10) { cin.get(ch); if (ch >= a && ch <= z) ch = ch 32; cout << ch << endl; count = count + 1; }
Counter-controlled
The number of iterations are given
char ch; int count; int n; // n is the number of times the body is to be repeated cin >> n; count = 0; while (count < n) { cin.get(ch); if (ch >= a && ch <= z) ch = ch 32; cout << ch << endl; count = count + 1; }
If x is odd or greater cin >> x; than 12, this loop will y = 0; never terminate! while (x <= 12) {
y = y + x; x = x + 2;
Sentinel-Controlled Loops
The number of iterations are not known up front. Check for a sentinel (a special entry)
cin >> lcv; // initlialize the lcv while (lcv != someSentinel) { cin >> lcv; }
lcv
cout << enter n/N to stop, any other key to continue: ; cin >> toContinue;
while (toContinue != n || toContinue != N) { cin << nextNumber; total = total + nextNumber; count = count + 1; cout << enter n/N to stop, any other key to continue: ; cin >> toContinue; }
cout << enter n/N to stop, any other key to continue: ; cin >> toContinue;
while (toContinue != n || toContinue != N) { cin << nextNumber; total = total + nextNumber; count = count + 1; cout << enter n/N to stop, any other key to continue: ; cin >> toContinue; }
Flag-controlled loops
secretNumber = // generate a random number between 1 and 1000 found = false; tries = 0;
while (!found) {
tries = tries + 1; cin >> myGuess;
if (myGuess == secretNumber) found = true; else if (myGuess > secretNumber) cout << The secret number is lower than your guess try again: ; else cout << The secret number is higher than your guess try again: ; } cout << You found the number in << tries << tries. << endl;
How to generate random numbers? See html documents in the shared folder.