What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control iteration Loop continues as long as condition is TRUE Types of Loop Testing Pretest Loops in C++ Endless loop Begin loop Pretest loop Test Condition true false Posttest loop Begin loop One pretest loop in C++ is the while loop A condition is used to control the loop The condition is put between parentheses Statements in loop End loop Statements in loop End loop Statements in loop Test Condition false true while (condition) statement; while (condition) statement ; statement ;... Loops can be... Count controlled repeat a specified number of times Event-controlled some condition within the loop body changes and this causes the repeating to stop Count-controlled loops They contain: An initialization of the loop control variable A condition to test for continuing the loop An update of the loop control variable to be executed with each iteration of the body 5 6
= ; // initialize loop variable while ( > 0) // test condition // repeated action --; // update loop variable = ; while ( > 0) --; 7 8 = ; while ( > 0) --; = ; while ( > 0) --; 9 0 = ; while ( > 0) --; = ; while ( > 0) --;
= ; while ( > 0) --; = ; while ( > 0) --; = ; while ( > 0) --; = ; while ( > 0) --; 5 6 = ; while ( > 0) --; = ; while ( > 0) --; 7 8
= ; while ( > 0) --; = ; while ( > 0) --; 9 0 = ; while ( > 0) --; 0 False = ; while ( > 0) --; 0 Event-controlled Loops = ; while ( > 0) --; 0 Done Sentinel controlled keep processing data until a special value which is not a possible data value is entered to indicate that processing should stop End-of-file controlled keep processing data as long as there is more data in the file Flag controlled keep processing data until the value of a flag changes in the loop body
s of Kinds of Loops A Sentinel-controlled Loop Count controlled loop Sentinel controlled loop End-of-file controlled loop Flag controlled loop Read exactly 00 blood pressures from the user. Read blood pressures until a special value (like -) selected by you is read. Read all the blood pressures from a file no matter how many are there. Read blood pressures until a dangerously high BP (00 or more) is read. 5 Sentinel value A special value of input that causes the program to stop a loop Must be a value that would not occur in the normal course of operation Requires a priming read if done with a while loop priming read means you read one set of data before the while 6 End-of-File Controlled Loop int bloodpressure, total = 0; cout << "Enter a blood pressure (- to stop ): "; cin >> bloodpressure; while (bloodpressure!= -) // while not sentinel total = total + bloodpressure; cout << "Enter a blood pressure (- to stop): "; cin >> bloodpressure; Depends on fact that a file goes into fail state when you try to read a data value beyond the end of the file Several ways to accomplish cout << total << endl; 7 8 Using the ifstream variable Combining the steps Uses a priming read The variable alone is the loop control variable If the stream has entered a fail state, it has a false, otherwise it has a true ifstream infile( data.txt ); int x; infile >> x; while(infile) //Statements infile >> x; The priming read can be done as part of the condition The logic is still the same as the previous slide ifstream infile( data.txt ); int x; while(infile >> x) //statements 9 0 5
eof Function eof function returns a true if the program has read past the end of the file; otherwise it returns a false Requires priming read ifstream infile( data.txt ); int x; infile >> x; while(!infile.eof()) //Statements infile >> x; Assignment With a partner write two loops that would read from the same file, money.dat, and print the contents to the screen. The program should loop until the end of the file is reached. Each of the two loops should use a different method Flag-controlled Loops Use a bool type flag variable and initialize it (to true or false) Use meaningful name for the flag A condition in the loop body changes the value of the flag Test for the flag in the loop test condition int bloodpressure, GoodReadings = 0; bool issafe = true; // initialize Boolean flag while (issafe) cin >> bloodpressure; if (bloodpressure >= 00) issafe = false; // change flag value else GoodReadings++; cout << GoodReadings << endl; Posttest Loops in C++ Posttest done with the do while statement. Also uses a condition placed in parentheses. do statement; while (condition); do statement ; statement ;... while (condition); 5 // display the numbers from to 0 // using the posttest do while loop = ; // initialize loop variable do // repeated action --; // update loop variable while ( > 0); // test condition 6 6
Sentinel-controlled loops with do while while vs. do while Does not require a priming read int bloodpressure = 0, total = 0; do total = total + bloodpressure; cout << "Enter a blood pressure (- to stop): "; cin >> bloodpressure; while (bloodpressure!= -); // while not sentinel cout << total << endl; while It is a Pretest loop. The loop condition is tested before executing the loop body. Loop body may not be executed at all. do while It is a Posttest loop. The loop condition is tested after executing the loop body. Loop body is always executed at least once. 7 8 Accumulating Loops often used to Count data values Sum data values Keep track of previous and current values This requires accumulating and ing 9 Accumulating (Cont..) Accumulating is keeping a running result Take the value of a variable, modify the value, and store it back in the original variable total = total + new; Any arithmetic operator (+ * / %) can be part of an accumulation total = total * new; Counting is a simple form of accumulation = + ; Make sure you INITIALIZE accumulation or ing variables 0 Accumulating (Cont..) Accumulation operators Shorthand for performing accumulation Same precedence & associativity as assignment // calculate the sum of the integers from to 0 // Initialize the ing and accumulating variables int number =, sum = 0; total += new; total -= new; total *= new; total /= new; total %= new; Equivalent statement total = total + new; total = total - new; total = total * new; total = total / new; total = total % new; while ( number <= 0) sum += number; // accumulating the sum // sum = sum + number; number += ; // ing, number = number + ; cout << "The sum is " << sum << endl; 7
Assignment Write a C++ program to calculate the factorial of 0. The for loop A specially designed -controlled loop for (initialization; test; updateer) statement; for (initialization; test; updateer) statement ; statement ;... The for loop Actions of the for spread out around the loop initialization occurs only ONCE at the start testing is the first repeated action of the loop (it gets done before the body each iteration) updateer occurs at the end of the loop body Initialization Test Updateer for ( = ; <= ; ++) Body cout << "Count = " << << endl; End 5 6 for ( = ; <= ; ++) cout << "Count = " << << endl; for ( = ; <= ; ++) cout << "Count = " << << endl; 7 8 8
for ( = ; <= ; ++) cout << "Count = " << << endl; for ( = ; <= ; ++) cout << "Count = " << << endl; 9 50 for ( = ; <= ; ++) cout << "Count = " << << endl; for ( = ; <= ; ++) cout << "Count = " << << endl; 5 5 for ( = ; <= ; ++) cout << "Count = " << << endl; for ( = ; <= ; ++) cout << "Count = " << << endl; 5 5 9
for ( = ; <= ; ++) cout << "Count = " << << endl; for ( = ; <= ; ++) cout << "Count = " << << endl; 55 56 False for ( = ; <= ; ++) cout << "Count = " << << endl; for ( = ; <= ; ++) cout << "Count = " << << endl; When the loop control condition is evaluated and has value false, the loop is said to be satisfied and control passes to the statement following the for structure. 57 58 Assignment for ( = ; <= ; ++) cout << "Count = " << << endl; Count = Write a program to ask the user to enter 5 integers and then find the maximum value. 59 60 0
Programming Error I What output do you expect from this loop? for ( = 0; < 0; ++) cout << "*"; What about this one? for ( = 0; < 0; ++); cout << "*"; Programming Error I (Cont..) The second loop in the previous slide does not produce any output. Why? The ; right after the ( ) means that the body statement is a null statement In general, the Body of the for loop is whatever statement immediately follows the ( ) That statement can be a single statement, a block, or a null statement Actually, the second code segment in the previous slide outputs one * after the loop completes its ing to 0 6 6 Programming Error II C++ will accept any simple data type as a er, but floating-point ers can lead to unexpected results Floating-point values are stored in E- notation and approximated to decimal values So the value.0 might be approximated to.00000000000 or 0.999999999999 6 Programming Error II (Cont..) float ; cout << "Values from 0 to in steps of 0.\n" << endl; cout << fixed << setprecision(); for ( = 0; <= ; += 0.) cout << << " "; cout << endl << "Final : " << << endl; Possible Values from 0 to in steps of 0. 0.00 0.0 0.0 0.0 0.0 0.50 0.60 0.70 0.80 0.90 Final :.00 6 Programming Error II (Cont..) cout << "Values from 0 to in steps of 0.\n" << endl; cout << fixed << setprecision(); for ( = 0; <= 0; ++) cout << /0.0 << " "; cout << endl << "Final : " << /0.0 << endl; Values from 0 to in steps of 0. 0.00 0.0 0.0 0.0 0.0 0.50 0.60 0.70 0.80 0.90.00 Final :.0 65 Nested Loops A loop within another is a nested loop Nest as deep as you want, but An inner loop must be entirely contained within an outer one If the loops are er controlled, each loop must have a different loop er variable Nested loops used often for rows and columns Outer loop controls the rows Inner loop controls the columns 66
of Nested Loops int column, row; for (row = ; row <= ; row++) for (column = ; column <= 5; column++) cout << setw() << row * column << " "; cout << endl; : 5 6 8 0 6 9 5 8 6 0 Assignment Write a program to display the following output: 5 67 68 Validation Loops Sometimes you may need to check for validity of input data The user can enter negative value where it is supposed to be positive (year) The user can enter a value that is outside the range of possible values (entering 0 for a test score) This can be done with validation loops Continue prompting the user for valid value as long as invalid value is entered 69 int score; cout << "Enter the test score: "; cin >> score; // test score should be between 0 and 00 while ( score > 00 score < 0) cout << "Invalid input, enter again: "; cin >> score; cout << endl << "The test score is " << score << endl; 70 Enter the test score: -8 Invalid input, enter again: 0 Invalid input, enter again: 89 The test score is 89 The break statement The break statement can be used with switch or any of the looping structures. It causes an immediate exit from the switch, while, do while, or for structure in which it appears. If the break is inside nested structures, control exits only the innermost structure containing it. 7 7
The continue statement The continue statement is valid only within loops. It terminates the current loop iteration, but not the entire loop. In a for or while loop, continue causes the rest of the body statement to be skipped - in a for statement, the update is done. In a do while loop, the exit condition is tested, and if true, the next loop iteration starts. Loop Testing and Debugging Beware of infinite loops - program doesn t stop Check loop termination condition, and watch for off-by- problem Trace execution of loop by hand with code walk-through Use debug output statements 7 7