Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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

2 Loops 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

3 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

4 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

5 C++ loops There are 3 types of C++ loops: while for do-while

6 while statement while (condition) { statement1; statement2; … }
Logical (Boolean) expression Logical (Boolean) expression “A>B” Relational operator “>” while (condition) { statement1; statement2; … } while (A > 5) { statement1; statement2; … } Loop body (compound statement) Loop body (compound statement)

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

8 for syntax for(init; test; update) { statement1; statement2; … } init
initializing expression test loop repetition condition update update expression Loop body (compound statement)

9 for loop example Important Steps!
// simpleFor.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; } cout << “sum: " << sum << endl; Important Steps! Initialize loop variable Test loop variable Update loop variable For loop handles all three steps!

10 do-while statement do { statement1; statement2; … } while (condition)
do { statement1; statement2; … } while (A > 5) Loop body (compound statement) Loop body (compound statement) Relational operator “>” Logical (Boolean) expression Logical (Boolean) expression “A>B” Note: do-while tests after the loop body – so it always executes at least once!

11 do-while loop example Important Steps!
// simpleDoWhile.cpp #include <iostream> using namespace std; // sum integers up to 5 int main() { int count=1, sum=0; do { cout << count << endl; sum += count; count++; } while(count <= 5); cout << “sum: " << sum << endl; } Important Steps! Initialize loop variable Test loop variable Update loop variable

12 Loop Usage Types of usage: Counter-controlled loops
Sentinel-controlled loops Flag-controlled loops Also End-of-file (EOF)-controlled loops

13 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

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

15 Counter-controlled for loop
// forCount.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; for statements are commonly used in counter-controlled loops

16 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 o the sentinel, the loop terminates

17 Sentinel-controlled while loop
//whileCount.cpp – compute average grade #include <iostream> using namespace std; #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 << "Average grade: " << sum/count << endl; Sentinel value is out of the range of valid values. When the user enters the sentinel value, the loop terminates.

18 Flag Controlled Loops Set the flag to false.
initialization Set the flag to false. While the flag is false, continue – otherwise (if true) terminate loop Perform some action.  Reset the flag to true if the anticipated event occurred, go back to step 2 Loop repetition condition update

19 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

20 Flag-controlled while loop
//whileFlag – 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; bool done= false; cout << "Guess the secret number (1-10)! "; while(!done) { cin >> guess; if( !(done= (guess == SECRET)) ) { cout << "Nope – try again! "; } cout << "You got it!!!" << endl; Flag is a bool and is initialized to false Loop tests to see if the flag is not entered by using the not operator (!) When the user enters the flag value, the loop terminates.

21 Loop form comparisons while for do-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 often 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 do-while convenient when at least one repetition of the loop body is required

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

23 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

24 break and continue example
// breakCont.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++; count=1; cout << "continue test:" << endl; if(i == count) { continue; } Outputs the following break test: 0 1 0 1 2 continue test:


Download ppt "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."

Similar presentations


Ads by Google