110 likes | 459 Views
Do While Loops!. December 14, 2010. For Today. Do While Loops Example Program Quiz on Friday!. Do While Loop. Is similar to the while structure. Tests the loop-continuation condition after the loop body is performed. The loop body will be executed at least once.
E N D
Do While Loops! December 14, 2010
For Today • Do While Loops • Example Program • Quiz on Friday!
Do While Loop • Is similar to the while structure. • Tests the loop-continuation condition after the loop body is performed. • The loop body will be executed at least once. • One interesting thing about the while loop is that if the loop condition is false, the while loop may not execute at all.
Do While Loop • When the loop terminated, executions continues with the statement after the while loop. • It is not necessary to use braces in the do/while loop if there is only one statement in the body.
Do While Syntax • Do While structure is: do statement; while (condition);
Do While Syntax • Do While structure is: do { statement; statement; } while (condition);
It is sometimes the case that we want a loop to execute at least once, such as when displaying a menu. To facilitate this, C++ offers the do while loop: Example: do { cout<< "Please make a selection: " << endl; cout << "1) Addition" << endl; cout<< "2) Subtraction" << endl; cout<< "3) Multiplication" << endl; cout<< "4) Division" << endl; cin>> nSelection; } while (nSelection != 1 && nSelection != 2 && nSelection!= 3 && nSelection != 4);
Another Example /*The following program fragment is an input routine that insists that the user type a correct response -- in this case, a small case or capital case 'Y' or 'N'. The do-while loop guarantees that the body of the loop (the question) will always execute at least one time.*/ char ans;do{cout<< "Do you want to continue (Y/N)?\n";cout<< "You must type a 'Y' or an 'N'.\n";cin >> ans;}while((ans !='Y')&&(ans !='N')&&(ans !='y')&&(ans !='n')); /*the loop continues until the user enters the correct response*/
Another Example do { cout<< "\nWhat is your age? "; cin>> age_user; cout<< "\nWhat is your friend's age? "; cin>> age_friend; cout>> "\nTogether your ages add up to: "; cout>> (age_user + age_friend); cout<< "\nDo you want to do it again? y or n "; cin>> loop_response; } while (loop_response == 'y');
The following program uses a do while loop to print the number from 1 to 10. #include<iostream.h> int main( ) { int counter = 1; do { cout<<counter<< „ „; } while ( ++counter <= 10); cout<<endl; return 0; }
Today’s exercise • Page 1.34, #2.21 Write a C++ program that utilizes looping and the tab excape (\t) to print the following table of values: N 10 * N 100 * N 1000 * N 1 10 100 1000 2 20 200 2000 3 30 300 3000 4 40 400 4000 5 50 500 5000