Loop n Loop l Loop While Loop Dowhile

  • Slides: 29
Download presentation
Loop

Loop

n. Loop l Loop ¡ While Loop ¡ Do-while Loop ¡ For Loop l

n. Loop l Loop ¡ While Loop ¡ Do-while Loop ¡ For Loop l Continue Statement l Conclusion

n. While Loop l Definition l General format l Example l Flow chart l

n. While Loop l Definition l General format l Example l Flow chart l Counter control repetition l Event control repetition

l While loop ¡ Action repeated while some condition remains true ¡ Psuedocode while

l While loop ¡ Action repeated while some condition remains true ¡ Psuedocode while there are more items on my shopping list Purchase next item and cross it off my list loop repeated until condition becomes false ¡ while

l General format when using while loops initialization; While( Loop. Continuation. Test){ statement; increment;

l General format when using while loops initialization; While( Loop. Continuation. Test){ statement; increment; } l Example int product = 2; while ( product <= 1000 ) product = 2 * product;

l Flowchart of while loop product <= 1000 false true product = 2 *

l Flowchart of while loop product <= 1000 false true product = 2 * product

l Counter-controlled ¡ Loop repetition repeated until counter reaches certain value ¡ Number of

l Counter-controlled ¡ Loop repetition repeated until counter reaches certain value ¡ Number of repetitions known ¡ Example A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // Class average program with counter-controlled repetition. #include <iostream> using std: : cout; using std: : cin; using std: : endl; // function main begins program execution int main() { int total; // sum of grades input by user int grade. Counter; // number of grade to be entered next int grade; // grade value int average; // average of grades // initialization phase total = 0; // initialize total grade. Counter = 1; // initialize loop counter

21 22 23 24 25 26 27 28 29 30 31 32 33 34

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 // processing phase while ( grade. Counter <= 10 ) { // loop 10 times cout << "Enter grade: "; // prompt for input cin >> grade; // read grade from user total = total + grade; // add grade to total grade. Counter = grade. Counter + 1; // increment counter } // termination phase average = total / 10; // integer division // display result cout << "Class average is " << average << endl; The counter gets incremented each time the loop executes. return 0; // indicate program ended successfully Eventually, the counter causes the loop to end. } // end function main l. Enter grade: 98 l. Enter grade: 76 l. Enter grade: 71 l. Enter grade: 87 l. Enter grade: 83 l. Enter grade: 90 l. Enter grade: 57 l. Enter grade: 79 l. Enter grade: 82 l. Enter grade: 94 l. Class average is 81

¡ Counter-controlled repetition requires Name of control variable/loop counter l Initial value of control

¡ Counter-controlled repetition requires Name of control variable/loop counter l Initial value of control variable l • Declares counter to be an integer int counter = 1; • Names counter • Sets counter to an initial value of 1 Condition to test for final value l Increment/decrement to modify control variable when looping l

l Event-controlled repetition ¡ Suppose problem becomes: Develop a class-averaging program that will process

l Event-controlled repetition ¡ Suppose problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run Unknown number of students l How will program know when to end? l ¡ Event Indicates “end of data entry” l Loop ends when special input l • it cannot be confused with regular input • -1 in this case

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Using the continue statement in a for structure. #include <iostream> #include <fstream> using std: : cout; using std: : endl; // function main begins program execution int main() { ifstream fp(“data 2. txt”); // open the file “data. txt” int num; Read all the information float grade, total=0; inside the file until the read String ssn; mark reaches the end of file. While ( !fp. eof()){ fp>>ssn >>grade; total = total+ grade; // sum of grades num++; } // end for structure while cout << num << “students with average grades: " << total/num << endl; return 0; // indicate successful termination }

Data 2. txt l 111 -23 -4561 56 l 123 -15 -1353 96 l

Data 2. txt l 111 -23 -4561 56 l 123 -15 -1353 96 l 131 -41 -2626 66 l 245 -51 -1256 76 l 151 -51 -6437 86 l 134 -59 -6714 90 l 626 -24 -2266 66 l 536 -24 -2525 60 9 students with average grades: 72. 8889

n. Do-While l General Loop format l Example

n. Do-While l General Loop format l Example

l General format when using do-while loops initialization; do{ statement; increment; }while( Loop. Continuation.

l General format when using do-while loops initialization; do{ statement; increment; }while( Loop. Continuation. Test); l Example int product = 2; do { product = 2 * product; } while ( product <= 1000 );

n. For Loop l General format l Example l Re-written l Initialization and increment

n. For Loop l General format l Example l Re-written l Initialization and increment for multiple variables l Applications

nfor Repetition Structure l General format when using for loops for ( initialization; Loop.

nfor Repetition Structure l General format when using for loops for ( initialization; Loop. Continuation. Test; increment ) statement l Example for( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; ¡ Prints integers from one to ten No semicolon after last statement

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // Counter-controlled repetition with the for structure. #include <iostream> using std: : cout; using std: : endl; // function main begins program execution int main() { // Initialization, repetition condition and incrementing // are all included in the for structure header. for ( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; return 0; // indicate successful termination } // end function main

1 2 3 4 5 6 7 8 9 10

1 2 3 4 5 6 7 8 9 10

loops can usually be rewritten as while loops l for initialization; while ( loop.

loops can usually be rewritten as while loops l for initialization; while ( loop. Continuation. Test){ statement increment; } l Initialization and increment for multiple variables, use comma-separated lists for (int i = 0, j = 0; j + i <= 10; j++, i++) cout << j + i << endl;

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // Summation with for. #include <iostream> using std: : cout; using std: : endl; // function main begins program execution int main() { int sum = 0; // initialize sum // sum even integers from 2 through 100 for ( int number = 2; number <= 100; number += 2 ) sum += number; // add number to sum cout << "Sum is " << sum << endl; // output sum return 0; // successful termination } // end function main l. Sum is 2550

l Program ¡ to calculate compound interest A person invests $1000. 00 in a

l Program ¡ to calculate compound interest A person invests $1000. 00 in a savings account yielding 5 percent interest. Assuming that all interest is left on deposit in the account, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula for determining these amounts: a = p(1+r)n ¡ p is the original amount invested (i. e. , the principal), r is the annual interest rate, n is the number of years and a is the amount on deposit at the end of the nth year

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Calculating compound interest. #include <iostream> using std: : cout; using std: : endl; using std: : ios; using std: : fixed; #include <iomanip> using std: : setw; using std: : setprecision; <cmath> header needed for the pow (program will not compile without it). #include <cmath> // enables program to use function pow // function main begins program execution int main() { double amount; // amount on deposit double principal = 1000. 0; // starting principal double rate =. 05; // interest rate

24 25 26 27 28 29 30 31 32 33 34 35 36 37

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 // output table column heads cout << "Year" << setw( 21 ) << "Amount on deposit" << endl; // set floating-point number format cout. self(ios: : fixed, ios: : floatfield); cout. self(ios: : showpoint); cout << setprecision( 2 ); // calculate amount on deposit for each of ten years for ( int year = 1; year <= 10; year++ ) { // calculate new amount for specified year amount = principal * pow( 1. 0 + rate, year ); // output one table row cout << setw( 4 ) << year << setw( 21 ) << amount << endl; } // end for return 0; // indicate successful termination } // end function main Sets the field width to at least 21 characters. If output less than 21, it is right-justified. pow(x, y) = x raised to the yth power.

Year 1 2 3 4 5 6 7 8 9 10 Amount on deposit

Year 1 2 3 4 5 6 7 8 9 10 Amount on deposit 1050. 00 1102. 50 1157. 63 1215. 51 1276. 28 1340. 10 1407. 10 1477. 46 1551. 33 1628. 89 Numbers are right-justified due to setw statements (at positions 4 and 21).

n. Continue l continue ¡ Used Statement statement in while, for, do/while ¡ Skips

n. Continue l continue ¡ Used Statement statement in while, for, do/while ¡ Skips remainder of loop body ¡ Proceeds with next iteration of loop l while and do/while structure ¡ Loop-continuation test evaluated immediately after the continue statement l for structure ¡ Increment expression executed ¡ Next, loop-continuation test evaluated

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Using the continue statement in a for structure. #include <iostream> using std: : cout; using std: : endl; // function main begins program execution int main() { // loop 10 times for ( int x = 1; x <= 10; x++ ) { Skips to next iteration of the loop. // if x is 5, continue with next iteration of loop if ( x == 5 ) continue; // skip remaining code in loop body cout << x << " "; // display value of x } // end for structure cout << "n. Used continue to skip printing the value 5" << endl; return 0; // indicate successful termination

26 27 } // end function main l 1 2 3 4 6 7

26 27 } // end function main l 1 2 3 4 6 7 8 9 10 l. Used continue to skip printing the value 5

n. Conclusion l While, do-while, and for loop l Counter-control and event-control l Many

n. Conclusion l While, do-while, and for loop l Counter-control and event-control l Many loops have three phases ¡ Initialization l Initialize the program variables ¡ Processing l Input data, adjusts program variables ¡ Termination l Evaluate the condition and stop loop if necessary