Control Structures Combine individual statements into a single

Control Structures • Combine individual statements into a single logical unit with one entry point and one exit point. • Used to regulate the flow of execution • Three types Sequential Selection Repetition - loops Professor John Carelli Kutztown University Source: Pearson Education

Loops are control structures that allow a programmer to repeat lines of code • Two parts • Loop – the control structure or loop statement • Loop body – the statements that are repeated in a loop Professor John Carelli Kutztown University Computer Science Department

Loops usage • A loop control variable is used to control when the loop ends. • The programmer must: • Initialize the loop control variable • Test the loop control variable • Update the loop control variable Professor John Carelli Kutztown University Computer Science Department

Loop control flow • The loop body will execute as long as the test condition (the logical expression) is true. • When the test condition (the logical expression) is false, the program will continue with the statement immediately after the loop body. Terminology • Each execution of the loop body is called an iteration Professor John Carelli Kutztown University Computer Science Department

C++ loops There are 3 types of C++ loops: • while • for • do-while Professor John Carelli Kutztown University Computer Science Department

while statement Logical (Boolean) expression “A < 5” Logical (Boolean) expression Relational operator “<” while (condition) { statement 1; statement 2; … } Professor John Carelli Loop body (compound statement) Kutztown University while (A < 5) { statement 1; statement 2; … } Loop body (compound statement) Computer Science Department

while loop example // simple. While. cpp #include <iostream> using namespace std; Important Steps! // sum integers up to 5 int main() { int count=1, sum=0; • Initialize loop variable • Test loop variable • Update loop variable while(count <= 5) { cout << count << endl; sum += count; count++; } What happens if one or more steps is missing/skipped? } Professor John Carelli Kutztown University cout << “sum: " << sum << endl; Computer Science Department

for syntax for(init; test; update) { statement 1; statement 2; … } Professor John Carelli Loop body (compound statement) Kutztown University initializing expression test loop repetition condition update expression Computer Science Department

for loop example Important Steps! • Initialize loop variable • Test loop variable • Update loop variable // simple. For. cpp #include <iostream> using namespace std; // sum integers up to 5 int main() { int sum=0; for(int i=1; i <= 5; i++) { cout << i << endl; sum += i; } For loop handles all three steps! } Professor John Carelli Kutztown University cout << “sum: " << sum << endl; Computer Science Department

do-while statement do { statement 1; statement 2; … } while (condition) Logical (Boolean) expression Loop body (compound statement) do { statement 1; statement 2; … } while (A < 5) Loop body (compound statement) Relational operator “<” Logical (Boolean) expression “A<B” Note: do-while tests after the loop body – so it always executes at least once! Professor John Carelli Kutztown University Computer Science Department

do-while loop example // simple. Do. While. cpp #include <iostream> using namespace std; Important Steps! // sum integers up to 5 int main() { int count=1, sum=0; • Initialize loop variable • Update loop variable • Test loop variable do { cout << count << endl; sum += count; count++; } while(count <= 5); • Note: update occurs before test! } Professor John Carelli Kutztown University cout << “sum: " << sum << endl; Computer Science Department

Loop Control Types of usage: • Counter-controlled loops • Sentinel-controlled loops • Flag-controlled loops • Also • End-of-file (EOF)-controlled loops Professor John Carelli Kutztown University Computer Science Department

Counter-controlled loop • Used when we can determine prior to loop execution how many loop repetitions will be needed to solve problem • An integer variable is generally used to maintain the count (i. e. number of loop iterations) • Number of iterations should appear as the final count Professor John Carelli Kutztown University Source: Pearson Education

Counter-controlled while loop //while. Count. cpp – compute average grade #include <iostream> using namespace std; #define NUMSTUDENTS 3 int main() { int count=0, grade; float sum=0; } Professor John Carelli while(count < NUMSTUDENTS) { cout << "Enter grade for student #" << count + 1 << ": "; cin >> grade; sum = sum + grade; count++; } cout << "Average grade: " << sum/count << endl; Kutztown University Computer Science Department

Counter-controlled for loop // for. Count. cpp - compute average grade #include <iostream> using namespace std; #define NUMSTUDENTS 3 int main() { int count, grade; float sum=0; } for(count=0; count < NUMSTUDENTS; count= count +1) { cout << "Enter grade for student #" << count + 1 << ": "; cin >> grade; sum = sum + grade; } cout << "Average grade: " << sum/count << endl; Professor John Carelli Kutztown University for statements are commonly used in counter-controlled loops Computer Science Department

Sentinel-Controlled Loops • A sentinel is a specific predetermined value used to terminate one type of event-controlled loop • It is the same type as the test variable • It is outside the range of valid values for the data • When the test variable is equal to the sentinel, the loop terminates Professor John Carelli Kutztown University Source: Pearson Education

Sentinel-controlled while loop //while. Count. cpp – compute average grade #include <iostream> using namespace std; Sentinel value is out of the range of valid values. #define SENTINEL -1 int main() { int count=0, grade; float sum=0; cout << "Enter grade for student #" << count + 1 << ": "; cin >> grade; } while(grade != SENTINEL) { sum = sum + grade; count++; cout << "Enter grade for student #" << count + 1 << ": "; cin >> grade; } cout << "Average grade: " << sum/count << endl; Professor John Carelli Kutztown University When the user enters the sentinel value, the loop terminates. Computer Science Department

Flag Controlled Loops initialization 1. Set the flag to false. 2. While the flag is false, continue – otherwise (if true) terminate loop 1. Perform some action. 2. Reset the flag to true if the anticipated event occurred, go back to step 2 Loop repetition condition update Professor John Carelli Kutztown University Computer Science Department

Flag Controlled Loops • Type bool variables often used as flags • Flag initialized to false before loop entry • Flag reset to true when a particular event occurs • Note: because flag is generally initialized as false, the loop condition uses ! (not) operator to reverse the flag’s value Professor John Carelli Kutztown University Source: Pearson Education

Flag-controlled while loop done is the flag variable It a bool and is initialized to false Loop tests the flag If not done, continue looping - use the not operator (!) When the user enters the correct value, done is set, and the loop terminates. Professor John Carelli Kutztown University //while. Flag – guess a number #include <iostream> using namespace std; #define SECRET 3 // guess the secret number // using a flag to terminate int main() { int guess=0; // store the guess bool done= false; // are we done? } cout << "Guess the secret number (1 -10)! "; while(!done) { cin >> guess; if( guess == SECRET ) done= true; else cout << "Nope – try again! "; } cout << "You got it!!!" << endl; Source: Pearson Education

Loop form comparisons • while • most commonly used when repetition is not counter controlled • condition test precedes each loop repetition • loop body may not be executed at all • for • • generally used to implement a counting loop also convenient for other loops with simple initialization and update steps condition test precedes the execution of the loop body may not be executed at all • do-while • convenient when at least one repetition of the loop body is required • condition test occurs after each loop repetition Professor John Carelli Kutztown University Source: Pearson Education

Loop Nesting // File: multiplication. cpp #include <iostream> #include <iomanip> using namespace std; • As with if statements, loop statements can be nested • Each time outer loop is repeated, the inner loop is restarted • loop control components are reevaluated and all required “inner loop” iterations are performed • Note: loops can be of different types! int main() { // Display table heading cout << " |"; for (int col. Head = 0; col. Head < 10; col. Head++) { cout << setw(3) << col. Head; } cout << endl; cout << " ----------------" << endl; } Professor John Carelli // Display table, row-by-row for (int row. Val = 0; row. Val < 10; row. Val++) { cout << setw(3) << row. Val << '|'; for (int col. Val = 0; col. Val < 10; col. Val++) { cout << setw(3) << row. Val * col. Val; } cout << endl; } return 0; Kutztown University Source: Pearson Education

break and continue Both interrupt normal flow of loop execution break • Causes the loop to exit immediately • Program execution continues at the first statement after the loop continue • The current iteration terminates immediately… • Only that iteration is affected!!! • The loop then moves on to the loop iteration condition and proceeds normally from there • i. e. iterates again if the termination condition has not been met Professor John Carelli Kutztown University Computer Science Department

break and continue example • Outputs the following // break. Cont. cpp #include <iostream> using namespace std; int main() { int count=1; cout << "break test: " << endl; while(count < 5) { for(int i=0; i<5; i++) { if(i == count) { break; } cout << " " << i; } cout << endl; count++; } break test: 0 01 0123 continue test: 0234 0124 0123 } Professor John Carelli Kutztown University count=1; cout << "continue test: " << endl; while(count < 5) { for(int i=0; i<5; i++) { if(i == count) { continue; } cout << " " << i; } cout << endl; count++; } Computer Science Department
- Slides: 24