# Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.

## Presentation on theme: "Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection."— Presentation transcript:

Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection repetition A sequence control structure uses compound statements (blocks) to specify sequential flow. A compound statement, a block of codes, is used to specify sequential flow. { statement1; statement2; statement3; } Sequence .

Selection Use if or switch statements to select one from many alternatives. if selection structure if (grade >= 60) cout << “Passes” << endl; if structure Grade >= 60 T print”Passed” F

If/else structure if / else selection structure if / else structure
if (grade >= 60) cout << “Passes” << endl; else cout << “Failed” << endl; if / else structure Grade >= 60 T print”Failed” print”Passed” F

if / else if / else Selection Structure
if ( grade >= 90 ) cout << “A grade” << endl; else if (grade >= 80) cout << “B grade” << endl; else if ( grade >= 70) cout << “C grade” << endl; else if ( grade >= 60) cout << “D grade” << endl; else cout << “F grade” << endl;

Conditions In general, condition has the following form: p1 op p2
Where p1 = variable p2 = variable / constant op = relational ( <, >, <=, >=) or equality operator (==, != ). Example: x <= 100 2. num != SENTINEL

Logical Operators (&&, ||, !)
With the help of logical operators you can form more complicated conditions or logical expressions. 3 logical operators are && (and), || (or), ! (not) Truth table for && operator Op2 Op1 && Op2 Op1 T F When both of the operands are true, the result will be true.

Logical Operator || (or)
When both operands are false, the result will be false, otherwise true. Truth table for || operator T F Op1 Op2 Op1 || Op2

Logical operator ! (not)
Has a single operand. Yields the logical complement or negation. Example: !(flag) it evaluates to 1 if flag = 0. Truth Table for !Operator T F Op1 !Op1

Operator Precedence Operator Precedence function calls highest ! + - &
! & * / % + - < <= >= > == != && || = lowest

Short-Circuit Evaluation
C++ evaluates only part of the expression. An expression a || b is true if a is true. C++ stops evaluating when it determines a =1. An expression a && b is false if a is false. C++ stops evaluating when it determines a = 0. This technique is called short-circuit evaluation.

Example !flag || (y + z >= x - z)
This expression is of the form a || b. a = !flag C++ would stop evaluating when it determines a = !flag = 1. From the truth table, the value of the expression does not depend on b if a = 1. !flag || (y + z >= x - z) = 1. x y z flag 3.0 4.0 2.0

Complementing a Logical Expressions
Temp is in the range 60 to 70 F, inclusive. Logical expression: <= temp && temp <= 70 Evaluation: (temp = 65): 1 && 1 => 1 (temp = 45): 0 && 1 => 0 Temp is outside the range 60 to 70 F (complement). Logical expression: ! (60 <= temp && temp <= 70) Alternative 60 > temp || temp > 70 Evaluation: (temp = 65): ! (1 && 1) => 0 (temp = 45): ! (0 && 1) => 1 Alternative (temp = 65): (0 || 0) => 0 (temp = 45): (1 || 0) => 1

De Morgan Theorem  60 > temp || temp > 70 Rule 1
Using De Morgan theorem, you can simplify the logical expression. Rule 1: ! (expr1 && expr2)  !expr1 || !expr2 Rule 2: ! (expr1 || expr2)  !expr1 && !expr2 Example: ! (60 <= temp && temp <= 70)  60 > temp || temp > Rule 1 !(temp < = 30 || (condition == ‘R’)  temp > 30 && condition != ‘R’ Rule 2

if and if /else statements
One alternative: if ( x != 0.0) product = product * x; Double alternatives: if (temp > 32.0) cout << “Above freezing” << endl; else cout << “Freezing” << endl;

Nested if statements Multiple alternatives if (x < 0.0) {
cout << “negative”; absx = -x; } else if (x == 0.0) cout<< “zero”; absx = 0.0; else cout << “positive”; absx = x; if (x < 0.0) { cout << “negative”; absx = -x; } else if (x == 0.0) cout << “zero”; absx = 0.0; cout << “positive”; absx = x;

Nested if vs.sequence of ifs
More readable and efficient if (x < 0.0) { cout << “negative”; absx = -x; } if (x == 0.0) cout << “zero”; absx = 0.0; if (x > 0.0) cout << “positive”; absx = x; Sequence of ifs Nested if if (x < 0.0) { cout << “negative”; absx = -x; } else if (x == 0.0) cout << “zero”; absx = 0.0; cout << “positive”; absx = x;

Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression can be type int or char, but not type double. First the expression is evaluated, then the list of case labels is searched until one matches the expression value. Statements following the matching case level are executed until a break statement is encountered. The break causes an exit from the switch statement. Execution continues with the statement that follows the closing brace of the switch statement body. If no case level matches the controlling expression value, the statement following the default label are executed. If there is no default label, the entire switch statement body is skipped.

case ‘A’ : cout << “Excellent” << endl; break; case ‘B’ : cout << “Good” << endl; case ‘C’ : cout << ”O.K.” << endl; case ‘D’ : cout << “Poor” << endl; case ‘F’ : cout << “Failed” << endl; default : cout << “Invalid letter grade” << endl; }

Flowchart for switch structure
Case A Excellent break Case B Good break Case C O.K. break Case D Poor break Case F Failed break invalid

Switch structure How many lines of output will be produced by the following program fragment ? int x; x = 0; switch (x) { case 0 : cout << "got 0“ << endl; case 1 : cout << "got 1“ << endl; case 2 : cout << "got 2“ << endl; default : cout << "do not have 0, 1 or 2“ << endl; }

Switch and if /else if /else structure
{ case 5 : c = c + b; case 2 : c = c + 2*b; break; case 3 : c = 7; case 6 : break; case 7 : c = c + 9; case 4 : case 1 : c *= c; default : c %= 2; } if (a == 5) { c = c + b; c = c + 2*b; } else if (a == 2) c = c +2*b; else if (a == 3) c = 7; else if (a == 6) ; else if (a == 7) c = c + 9; else if ((a == 4) || (a == 1) c * = c; else c % = 2;

if /else and switch structures
if / else structure Switch structure Switch (i) { case 1 : case 2 : j = k - 2; k += 3; break; case 3 : j = k + 3; ++k; j = k - 2; k += 3; case 4 : j = k + 3; default : j = k + 5; } if ((i > 0) && ( i < 5)) { if ( i > 2) j = k + 3; ++k; } if ( i < 4) j = k - 2; k += 3; else j = k + 5;

Repetition & Loop Statement
A type of program control structure. A loop is a group of instructions the computer executes repeatedly while some loop-continuation condition remains true. Be sure to verify that a loop’s repetition condition will eventually become false, otherwise an infinite loop may result. Three C++ loop control structures are: while do / while for

Flow Diagram of Loop Choice
No No loop required Any steps repeated ? Yes Use of the conditional loop: - sentinel-controlled End-of-file-controlled Flag-controlled - input validation - general conditional Know in advance how many times to repeat ? No Yes Use a counting loop

Counter-Controlled Repetition
A control variable is used to count the number of repetitions. The control variable is incremented (or decremented) each time the group of instructions is performed. When the value of the control variable indicates that the correct number of repetitions has been performed, the loop terminates. Counter controlled repetition requires: Name of a control variable (loop counter). Initial value of the control variable. Increment (or decrement) by which the control variable is modified each time through the loop. Condition that tests for the final value of the control variable.

Counter-Controlled repetition with the while Loop
#include <iostream> int main() { int counter = 1; // intitialization while (counter <= 10) // repetition condition cout << counter << endl; ++counter; // increment } return 0;

Flowchart for while structure
++counter <= 10 cout << counter << endl; T F

Do/While Repetition Structure
#include <iostream> int main() { int counter = 1; do cout << setw(2) << counter ; } while (++counter <= 10) cout << endl; return 0; } Do-while always executes at least once. Use a do-while only when there is a possibility of zero loop iterations. output

Flowchart for do / while Structure
++counter <= 10 cout << counter; T F

Counter-Controlled repetition with the for Loop
#include <iostream> int main() { int counter; for (counter = 1; counter <= 10; counter++) initialization repetition condition increment cout << counter << endl; return 0; }

Flowchart of a for structure
Establish initial value of control variable counter = 1 Test if final value of control variable has been reached counter <= 10 T cout << counter; counter++ F Body of loop Increment the control variable

The Break Statement #include <iostream> Output int main() {
int x; for (x = 1; x <= 10; x++) if (x == 5) break; // break loop only if x == 5 cout << setw(2) << x; } cout << endl; cout << “Broke out loop at x == “ << x << endl; return 0; Output Broke out of loop at x == 5

The Continue Statement
#include <iostream> int main() { int x; for (x = 1; x <= 10; x++) if (x == 5) continue; // skip remaining code in loop // only if x == 5 cout << x; } cout << endl; cout << “Used continue to skip printing the value 5” << endl; return 0; Output Used continue to skip printing the value 5

Sentinel-Controlled Loop
Sentinel values are used to control repetition when the precise number of repetitions is not known in advance. The loop includes statements that obtain data each time the loop is performed. Sentinel value indicates “end of data”. Sentinel is entered after all regular data items have been supplied to the program. Sentinels must be distinct from regular data items.

Sentinel-Controlled while Loop
#include <iostream> const SENTINEL = - 99; int main() { int sum = 0, score; cout << “Enter first score or “ << SENTINEL << “to quit”<< endl; cin >> score; while (score != SENTINEL) sum += score; cout << “Enter next score or “<< SENTINEL<< “to quit”<< endl; cin>> score; } cout << "Sum of exam scores is “ << sum << endl; return (0);

End-Of-File-Controlled Loop
#include <iostream> #include <fstream> int main() { char inchar; ifstream myinfile; myinfile.open("C:input.dat"); if (!myinfile) cout <<"cannot open file"<< endl; return 1; }

End-Of-File-Controlled Loop
myinfile.get(inchar); while (myinfile) { cout <<inchar; } return 0;

Flag-Controlled Loop #include <iostream> int main() { int num;
bool found = false; while (!found) cout << “Enter a number” << endl; cin >> num; if (num == 4) cout << “Target found”<< endl; found = true; }

Validating input using do-while statement
Get data value. If data value isn’t in the acceptable range, go back to first step. do { cout << “Enter a letter from A through E>”; cin >> letter_choice; } while (letter_choice < ‘A’ || letter_choice > ‘E’);

General Conditional Loop
Initialize loop control variable. As long as exit condition hasn’t been met, continue processing. for ( radiation_lev = init_radiation; radiation_lev > min_radiation; radiation_lev /= 2.0) { if (radiation_lev > SAFE_RAD) cout << “Unsafe”<< endl; else cout << “Safe” << endl; }

Download ppt "Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection."

Similar presentations