450 likes | 586 Views
Loops. Chapter 5. Overview. Loop Statement Syntax Loop Statement Structure: while, for, do-while Count-Controlled Loops Nested Loops Loop Testing and Debugging. What is a loop?. A loop is a repetition control structure
E N D
Loops Chapter 5
Overview • Loop Statement Syntax • Loop Statement Structure: while, for, do-while • Count-Controlled Loops • Nested Loops • Loop Testing and Debugging
What is a loop? • A loop is a repetition control structure • it causes a single statement or compound statement to be executed repeatedly • Repetition ends when • The statement is executed a predetermined number of times (count controlled) • A logical condition which controls the loop becomes false a result of the repetition statement (event controlled)
While Statement while (y > 0) y = y – 1; while (y > 0); while (y > 0) { y = y – 1; a = a + y; } • The loop body can be a single statement, a null statement (empty), or a compound statement (block).
While loop (flow chart) • When the expression is tested and found to be false, the loop is exited and control passes to the statement which follows the loop body. FALSE Expression TRUE Body Statement(s)
Count-controlled loops • To maintain a count control loop, the loop code must • initialize the loop control variable • compare the loop control variable to the predetermined number of loop iterations • update the loop control variable after each iteration
Count-controlled Loop int count; count = 4; //initialize loop variable while (count > 0) // test expression { cout << count << endl; //repeated action count--;//update loop variable } cout << “Done” << endl;
count Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT
count 4 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT
count 4 Count-controlled Loop int count ; count = 4; while (count > 0) TRUE { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT
count 4 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4
count 3 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4
count 3 Count-controlled Loop int count ; count = 4; while (count > 0) TRUE { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4
count 3 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4 3
count 2 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4 3
count 2 Count-controlled Loop int count ; count = 4; while (count > 0) TRUE { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4 3
count 2 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4 3 2
count 1 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4 3 2
count 1 Count-controlled Loop int count ; count = 4; while (count > 0) TRUE { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4 3 2
count 1 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4 3 2 1
count 0 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4 3 2 1
count 0 Count-controlled Loop int count ; count = 4; while (count > 0) FALSE { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4 3 2 1
count 0 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count --; } cout << “Done” << endl ; OUTPUT 4 3 2 1 Done
Finding a prime number int index = 2, number; bool flag =false; cout << "Enter number: "; cin >> number; while (index < number && flag == false) { flag = ((number % index) == 0); index++; } if (flag) cout << number << " is not prime\n"; else cout << number << " is prime\n";
Event-controlled Loops • More general than a count controlled loop, event-controlled loops repeat until the test condition becomes false from statements in the loop body • Number of iterations not generally known in advance • Possible strategies • Sentinel controlled • keep processing data until a special value, which is not a valid data value, is entered to indicate that processing should stop • Flag controlled • keep processing data until the value of a flag changes in the loop body
Sentinel total = 0; thisBP = 0; while (thisBP != -1) // while not sentinel {cout << "Enter a blood pressure"; cout << " (-1 to stop ): ";cin >> thisBP; if (thisBP!=-1) total = total + thisBP; } cout << total;
Flag countGoodReadings = 0; isSafe = true; // initialize Boolean flag while (isSafe) { cin >> thisBP; if (thisBP >= 200) isSafe = false; // change flag valueelse countGoodReadings++; } cout << countGoodReadings << endl;
Nested Loops int i=1, j; while(i<=10) { j=1; while (j<=10) { cout << i*j << " "; j++; } i++; cout << endl; } Output 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 …
Early loop termination: break while ( boolean expression) { // do many activities if ( some condition is true) break; // do interesting stuff otherwise } • break can be used in any type of loop • break allows the loop to be terminated • In the case of nested loops, the inner-most loop which contains the break statement is terminated out of loop
Example: Maximum (while with break) int value, max=0; while(true) { cout << "Enter a value (-1 to stop): "; cin >> value; if(value > max) max = value; if(value==-1) break; } cout << "The maximum value found is " << " is " << max << endl;
Example: Maximum (while WITHOUT break) int value=0, max=0; while( value!=-1) { cout << "Enter a value (-1 to stop): "; cin >> value; if(value > max) max = value; } cout << "The maximum value found is " << " is " << max << endl;
Skipping an iteration: continue while (boolean expression) { // do many activities if ( some condition is true) continue; // do other interesting stuff otherwise } • continue can be used in any type of loop • as a result of continue, rest of the loop is skipped for that iteration • Only portions of the immediate loop surrounding the continue statement is skipped
Example of continue int i = 100; int index = 0; while (index <= i) { index++; if ( index % 20 != 0) continue; cout << index << " is a multiple of 20"; }
Example NOT using continue int i = 100; int index = 0; while (index <= i) { index++; if ( index % 20 == 0) cout << index << " is a multiple of 20"; }
Control Flow: for statement • The for statement has the form for (initialization; test expression; update) {// loop body } • The order of operation of for statement • execute the initialization statement(s) • Test the boolean expression • If the boolean expression is true, • execute the loop body • execute the update statement • go to Test • Else • execute 1st statement after the loop body
Condition Initialization Body For loop (flow chart) • The initialization occurs when the for loop is entered, NOT on each iteration • The update statement is executed after the body on each iteration • The condition is tested before each iteration For (init; condition; update) {} FALSE True TRUE Update
Control Flow: for statement for (int i= 0; i < 10; i++) cout << “Value of i is “ << i << endl; for (int i = 0, j = 4; i < 3 && j >2; i++, j--) { //action } for ( ; i < 3 && j > 2; i++, j--) { //action } // no initialization
Control Flow: for statement for ( ; i < 3 && j > 2; ) { //action } // no initialization or update for ( ; ; ) { //action } // infinite loop
Count-controlled Loop: for for (int count = 4; count > 0; count --) { cout << count << endl; //repeated action } cout << “Done” << endl; • Exact same behavior as the while example, but with a more compact form
Loop Testing and Debugging • Test data should test all sections of program • Boundary conditions • All branches • Beware of infinite loops -- program doesn’t stop • Check loop termination condition • watch for “off-by-1” problem • Don’t compare real numbers for equality • Trace execution of loop by hand with code walk-through
Do-While Statement do y = y – 1; while (y > 0); do { y = y – 1; a = a + y; } while (y > 0); • The loop body always executes at least once
Do-While loop (flow chart) • When the expression is tested and found to be false, the loop is exited and control passes to the statement which follows the loop body. True Body Statement(s) Expression False
Example: N! (do-while) int number, factorial, n; cout << "Enter number: "; cin >> number; factorial = 1; n = 1; do{ factorial *= n; n++; }while(n <= number); cout << "The factorial of " << number << " is " << factorial << endl;
Example: N! (while) int number, factorial, n; cout << "Enter number: "; cin >> number; factorial = 1; n = 1; while(n <= number){ factorial *= n; n++; } cout << "The factorial of " << number << " is " << factorial << endl;
Example: N! (for) int number, factorial, n; cout << "Enter number: "; cin >> number; factorial = 1; for (n=1; n<=number; n++) factorial *= n; cout << "The factorial of " << number << " is " << factorial << endl;