Control Structures Control structures control the flow of

  • Slides: 40
Download presentation
Control Structures • Control structures control the flow of program execution. • 3 types

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. { statement 1; statement 2; statement 3; } Sequence .

Selection • Use if or switch statements to select one from many alternatives. •

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

If/else structure • if / else selection structure if (grade >= 60) cout <<

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

if / else Selection Structure if ( grade >= 90 ) cout << “A

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 1. In general, condition has the following form: 2. p 1 op p

Conditions 1. In general, condition has the following form: 2. p 1 op p 2 3. Where p 1 = variable 4. p 2 = variable / constant 5. op = relational ( <, >, <=, >=) or 6. equality operator (==, != ). 7. Example: 1. x <= 100 8. 2. num != SENTINEL

Logical Operators (&&, ||, !) • With the help of logical operators you can

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 Op 1 T Op 2 T Op 1 && Op 2 T T F F F 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

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

Logical operator ! (not) • Has a single operand. • Yields the logical complement

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 Op 1 !Op 1 T F F T

Operator Precedence Operator function calls ! + - & * / % + <

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

Short-Circuit Evaluation • • • C++ evaluates only part of the expression. An expression

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 x y z flag 3. 0 4. 0 2. 0 0 !flag ||

Example x y z flag 3. 0 4. 0 2. 0 0 !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.

Complementing a Logical Expressions • Temp is in the range 60 to 70 F,

Complementing a Logical Expressions • Temp is in the range 60 to 70 F, inclusive. Logical expression: 60 <= 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: Alternative (temp = 65): ! (1 && 1) => 0 (temp = 45): ! (0 && 1) => 1 (temp = 65): (0 || 0) => 0 (temp = 45): (1 || 0) => 1

De Morgan Theorem • Using De Morgan theorem, you can simplify the logical expression.

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

if and if /else statements • One alternative: if ( x != 0. 0)

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

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; } else { cout << “positive”; absx = x; }

Nested if vs. sequence of ifs if (x < 0. 0) Sequence { of

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

Switch structure • Switch structure selects one from several alternatives depending on the value

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.

Switch structure switch (grade) { case ‘A’ : cout << “Excellent” << endl; break;

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

Flowchart for switch structure Case A Excellent break Case B Good break Case C

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

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 structure switch (a) { case 5 : c = c

Switch and if /else structure switch (a) { case 5 : c = c + b; case 2 : c = c + 2*b; break; case 3 : c = 7; break; case 6 : break; case 7 : c = c + 9; break; case 4 : case 1 : c *= c; break; default : c %= 2; break; } if / else if /else 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 if ((i > 0) &&

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

Repetition & Loop Statement • A type of program control structure. • A loop

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 Any steps repeated ? No Yes Know in advance

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

Counter-Controlled Repetition • A control variable is used to count the number of repetitions.

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 =

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

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

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

Do/While Repetition Structure #include <iostream> Do-while always executes int main() at least once. {

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

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

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

Counter-Controlled repetition with the for Loop #include <iostream> int main() { int counter; for

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

Flowchart of a for structure counter = 1 Establish initial value of control variable

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

The Break Statement #include <iostream> Output int main() 1234 { Broke out of loop

The Break Statement #include <iostream> Output int main() 1234 { Broke out of loop at x == 5 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; }

The Continue Statement 1. #include <iostream> Output 2. int main() 1 2 3 4

The Continue Statement 1. #include <iostream> Output 2. int main() 1 2 3 4 6 7 8 9 10 3. { Used continue to skip printing the value 5 4. int x; 5. for (x = 1; x <= 10; x++) 6. { 7. if (x == 5) 8. continue; // skip remaining code in loop 9. // only if x == 5 10. cout << x; 11. } 12. cout << endl; 13. cout << “Used continue to skip printing the value 5” << endl; 14. return 0; 15. }

Sentinel-Controlled Loop • Sentinel values are used to control repetition when – the precise

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

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.

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; myinfile. get(inchar); } return 0;

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

Flag-Controlled Loop #include <iostream> int main() { int num; bool found = false; while

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

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

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; }