Chapter 2 - Control Structures

Chapter 2 - Control Structures

Pseudocode When designing an ALGORITHM to solve a problem, Pseudocode, can be used. Artificial, informal language used to develop algorithms Similar to everyday English Not executed on computers Used to think out program before coding Easy to convert into C++ program Only executable statements No need to declare variables 2.4 Control Structures Sequential execution Statements executed in order Transfer of control Next statement executed not next one in sequence 3 control structures (Bohm and Jacopini) Sequence structure

Programs executed sequentially by default Selection structures if, if/else, switch Repetition structures while, do/while, for 2.4 Control Structures Flowchart Graphical representation of an algorithm Special-purpose symbols connected by arrows (flowlines) Rectangle symbol (action symbol) Any type of action Oval symbol Beginning or end of a program, or a section of code (circles) Single-entry/single-exit control structures Connect exit point of one to entry point of the next Control structure stacking

2.5 if Selection Structure Selection structure Choose among alternative courses of action Pseudocode example: If students grade is greater than or equal to 60 Print Passed If the condition is true Print statement executed, program continues to next statement If the condition is false Print statement ignored, program continues Indenting makes programs easier to read C++ ignores whitespace characters (tabs, spaces, etc.) 2.5 if Selection Structure Translation into C++ If students grade is greater than or equal to 60 Print Passed if ( grade >= 60 ) cout << "Passed";

Diamond symbol (decision symbol) Indicates decision is to be made Contains an expression that can be true or false Test condition, follow path if structure Single-entry/single-exit 2.5 if Selection Structure Flowchart of pseudocode statement A decision can be made on any expression. grade >= 60 true print Passed zero - false nonzero - true

Example: false 3 - 4 is true 2.6 if/else Selection Structure if Performs action if condition true if/else Different actions if conditions true or false Pseudocode if students grade is greater than or equal to 60 print Passed else print Failed C++ code if ( grade >= 60 ) cout << "Passed";

else cout << "Failed"; 2.6 if/else Selection Structure Ternary conditional operator (?:) Three arguments (condition, value if true, value if false) Code could be written: cout << ( grade >= 60 ? Passed : Failed ); Condition false print Failed Value if true grade >= 60 Value if false true print Passed

2.6 if/else Selection Structure Nested if/else structures One inside another, test for multiple cases Once condition met, other statements skipped if students grade is greater than or equal to 90 Print A else if students grade is greater than or equal to 80 Print B else if students grade is greater than or equal to 70 Print C else if students grade is greater than or equal to 60 Print D else Print F 2.6 if/else Selection Structure Example if ( grade >= 90 )

cout << "A"; else if ( grade >= 80 ) cout << "B"; else if ( grade >= 70 ) cout << "C"; else if ( grade >= 60 ) cout << "D"; else cout << "F"; // 90 and above // 80-89 // 70-79 // 60-69 // less than 60 2.6 if/else Selection Structure Compound statement Set of statements within a pair of braces if ( grade cout << else {

cout << cout << >= 60 ) "Passed.\n"; "Failed.\n"; "You must take this course again.\n"; } Without braces, cout << "You must take this course again.\n"; always executed Block Set of statements within braces 1.25 Decision Making: Equality and Relational Operators Standard algebraic equality operator or

relational operator C ++ equality or relational operator Example of C ++ condition Meaning of C ++ condition > > x > y x is greater than y <

< x < y x is less than y >= x >= y x is greater than or equal to y <= x <= y x is less than or equal to y

= == x == y x is equal to y != x != y x is not equal to y Relational operators Equality operators Values of Relational Expressions

a-b ab a <= b a >= b positive 0 1 0 1 zero

0 0 1 1 negative 1 0 1 0 Equality Operators Exmaples Valid ----------------------------------------c == A

k != -2 y == 2 * z 5 Not Valid ---------------------------------------a=b // assignment statement a==b1 // space not allowed y =! z // this is equivalent to y = (!z) 2003 Prentice Hall, Inc. All rights reserved. Numerical Accuracy Many decimal numbers cannot be exactly represented in binary by a finite number of bits. Thus testing for exact equality can fail. Use the technique: |operand1 - operand2| < epsilon Ex.

x/y == 17 abs(x/y - 17) < 0.000001 * Logical Operators Negation (unary) ! Logical and && Logical or || * Logical Operators: Examples Valid

(a < 9) && (b> 7) ((a< 6) || (b > 8)) && (c< 7) !(a < b) && c > k 3 && (-2 * a + 7) a > l && a>9 | | b 9 & b<8 &b Not Valid // one operand missing // extra space not allowed // this is a bitwise operation // the address of b ** Logical Operators: Examples int a = 0, b = 3, c = 1, d =4; a && !c || d F

F b b b T *** Logical Operators Expression !(a == b) !(a == b || a == c) !(a == b && c > d) Expression Equivalent a != b

a != b && a != c a != b || c <= d *** Operator Precedence and Associativity Operators Associativity not () ++(postfix) ! --(postfix) + (unary) - (unary) ++ (prefix) -- (prefix) left to right right to left left to right left to right left to right left to right left to right left to right right to left

right to left left to right arithmetic * / % + <= > >= relational < == != && logical || ?: = += -= *= /= , (comma operator) etc.

The Empty Statement The empty statement is written as a semicolon. Example: ; // an empty statement Other statements: a = b; // an assignment statement a + b + c; // legal, no useful work done cout << a() << "\n"; // a function call Common Errors! == means equality =

used for assignment FALSE is zero TRUE is nonzero Boolean operators give a Boolean result ** 2.16 switch Multiple-Selection Structure switch Test variable for multiple values Series of case labels and optional default case switch ( variable ) { case value1: statements break; case value2: case value3: statements break; default: statements

break; } // taken if variable == value1 // necessary to exit switch // taken if variable == value2 or == value3 // taken if variable matches no other cases 2.16 switch Multiple-Selection Structure case a true case a action(s) break case b action(s)

break case z action(s) break false case b true false . . . case z false default action(s)

true The switch Statement Syntax switch (expression) { no ; case value1: statement1; use : break; case value2: statement2; break; case valuen: statementn; break; default: statement; }

** The switch Statement Syntax switch (expression) { no ; case value1: statement1; use : break; break case value2: statement2; break; break case valuen: statementn; break;

break default: default statement; } char let_grd; cout <> let_grd; switch (let_grd) { case A: cout << Congratulations!; break; case B: cout << Good job!; break; case C: cout << ok, but you can do better!; break; cont.

The switch Statement case D: cout << Better luck in PMII; break; case F: cout << Have fun in summer school!; break; default: cout << You entered an invalid grade.; } next statement The switch and Break Statement switch (let_grd) { case A: cout << Congratulations!; break; case B: cout << Good Job!; break;

case C: cout << OK, but you can do better!; break; case D: cout << Better luck in PMII!; break; case E: cout << Have fun in summer school!; break; default: cout << You entered an invalid grade.; } The break Statement switch (let_grd) { case A: case B: cout << Good Work; break; case C: cout << ok!; break;

case D: case E: cout << Have fun in summer school!; } The break Statement switch (let_grd) { case A: case a: case B: case b: cout << Good Work; break; case C: case c: cout << OK!; break; etc.

Recently Viewed Presentations

  • &quot;Week&quot; 12: November 20, 2017

    "Week" 12: November 20, 2017

    "Week" 12-13: November 20, 27-30 and December 1, 2017. Unit II "opening acts" work, plus Oral History Project reminders, delivery, & product sharing
  • Biomechanics - Evarzesh

    Biomechanics - Evarzesh

    The coordinates of the center of gravity can be found from the sum of the torques acting on the individual particles being set equal to the torque produced by the weight of the object Find your center of gravity (Example...
  • Colegio El Amparo - Clase3d

    Colegio El Amparo - Clase3d

    Plants, monerans and protista. Plants, animals and monerans. How do you call single celled organisms that can photosinthesize or respire? (Their nucleus lacks a membrane, but their cells have a protective wall) Protozoans. ... Colegio El Amparo
  • Skin Pigmentation: Cell Biology slide version 1.0 www.evo-ed.org

    Skin Pigmentation: Cell Biology slide version 1.0 www.evo-ed.org

    Human skin has three basic layers (from outside to inside): the epidermis, the dermis and the hypodermis. Since skin color is expressed in the epidermis, we will focus our discussion on cells of that layer. ... Diagram modified from Wu...
  • Laws (no longer in effect) in South Africa that physically ...

    Laws (no longer in effect) in South Africa that physically ...

    Laws (no longer in effect) in South Africa that physically separated different races into different geographic areas. Apartheid. ... Creolized language. ... Laws (no longer in effect) in South Africa that physically separated different races into different geographic areas Last...
  • Proclaim Westminster

    Proclaim Westminster

    Proclaim Westminster The Diocese has been on a journey to respond to the Pope's call of discernment to see how we can in our parishes reflect upon our gifts and discern more deeply how we might best share the good...
  • The Crucible - Weebly

    The Crucible - Weebly

    Salem Witch Trials. In writing The Crucible, Miller went to the source of the Salem Witch Hunts and read transcripts of the trials.His play is not historically accurate, but does loosely follow the real events. In 1692 nineteen men and...
  • Chasing Lincoln&#x27;s Killer Vocabulary

    Chasing Lincoln's Killer Vocabulary

    Chapter 7. Salvation (n) 116 - Bonds (n) 119 - Thicket (n) 120 - Fugitives (n) 120 - Confided (v) 121 - Carbine (n) 127 - Deliverance from the power and effects of sin.