User Tools

Site Tools


cplusplus:control_structures_selection

View page as slide show

Control Structures: Selection

Mithat Konar

Introduction

  • Control structures are used to affect how statements are executed.
    • Sometimes also called flow control.

Control structures in C++

  • Three kinds of control structures are used in C++ and many other languages:
    • Sequence
      • Statements are executed one after the other.
      • This is C++'s default behavior!
    • Selection structures
      • Used to choose among alternative courses of action.
      • “Making decisions”
    • Repetition structures
      • Used to repeat a set of instructions.
      • “Looping”

Single-entry/single-exit structures

  • Control structures that are entered from one point and exited from one point.
  • Connect the exit point of one control structure to entry point of the next: control-structure stacking.
  • Makes programs easy to build.

Selection structures

  • Four selection structures available in C++:
    • if
    • if/else
    • nested if/else
    • switch
  • Also has a ternary conditional operator that performs selection.

if selection structure

  • Used to do something if some condition is “true”.
  • Pseudocode example:
    if student’s grade is greater than 60
      print "Passed"

    If the condition is true the print statement is executed and program goes on to next statement. If the condition is false the print statement is ignored and the program goes onto the next statement.

  • The if structure is a single-entry/single-exit structure.

if syntax

  • C++ syntax:
    if (<expression>)
      <statement>;
  • Example:
    if (grade > 60)
      cout << "Passed" << endl;

Relational operators

  • Relational operators are used to compare values and return a true or false value.
  • A value that is either true or false is a Boolean value.
    • bool type in C++

C++ relational operators

  • C++ supports the following relational operators:
    • > greater than
    • < less than
    • >= greater than or equal to
    • <= less than or equal to
    • == equal to (equality)
    • != not equal to (inequality)
    • Note: Do not confuse the == equality operator with the = assignment operator. This is a common mistake and can cause hard-to-find errors!

Order of precedence

operator associativity type
() left to right parenthesis
* / % left to right multiplicative
+ - left to right additive
<< >> left to right stream insertion/extraction
< <= > >= left to right relational
== != right to left equality
= right to left assignment

if/else selection structure

  • Used to do one thing if some condition is “true”, something else if the condition is “false”.
  • Pseudocode example:
    if student’s grade is greater than or equal to 60
      print “Passed”
    else
      print "Failed"

    If the condition is true the “Passed” print statement is executed and the program goes on to next statement. If the condition is false the “Failed” print statement is executed and the program goes onto the next statement.

  • The if/else structure is a single-entry/single-exit structure.

if/else syntax

  • C++ syntax:
    if (<expression>)
      <statement>;
    else
      <statement>;
  • Example:
    if (grade >= 60)
      cout << "Passed" << endl;
    else
      cout << "Failed" << endl;

Nested if/else selection structure

  • Placing if/else selection structures inside if/else selection structures can be used to test for multiple cases.

Nested if/else pseudocode

  • “Logical” formatting:
    if student’s grade is greater than or equal to 90
      print "A"
    else
      if student’s grade is greater than or equal to 80
        print "B"
      else
        if student’s grade is greater than or equal to 70
          print "C"
        else
         if student’s grade is greater than or equal to 60
           print "D"
         else
           print "F"

Nested if/else pseudocode

  • “Readability” formatting:
    if student’s grade is greater than or equal to 90
      print "A"
    else if student’s grade is greater than or equal to 80
      print "B"
    else if student’s grade is greater than or equal to 70
      print "C"
    else if student’s grade is greater than or equal to 60
      print "D"
    else
      print "F"

Nested if/else syntax

  • C++ syntax:
    if (grade >= 90)
      cout << "A" << endl;
    else if (grade >= 80)
      cout << "B" << endl;
    else if (grade >= 70)
      cout << "C" << endl;
    else if (grade >= 60)
      cout << "D" << endl;
    else
      cout << "F" << endl;

Compound statements

  • A simple statement in C++ is any statement that ends with a semicolon:
    cout << "This is a simple statement." << endl;
  • A compound statement is a set of simple statements placed between curly brackets:
    {
      x = 3 * y;
      cout << "The magic number is: " << x << endl;
    }

Compound statement example

  • A compound statement can be used anywhere a simple statement can be used, for example in an if statement:
    if (grade >= 60)
      cout << "Passed." << endl;
    else
    {
      cout << "Failed." << endl;
      cout << "You must take this course again." << endl;
    }
  • Without the brackets, the statement
    cout << "You must take this course again." << endl;

    would be executed no matter what.

Blocks

  • A compound statement with variable declarations is called a block.
  • C++ example:
    if (grade >= 60)
      cout << "Passed." << endl;
    else
    {
      char yourGrade;
      yourGrade = 'F';
      cout << "You received a grade of " << yourGrade << endl;
      cout << "You must take this course again." << endl;
    }

Logical operators

  • Logical operators are used to implement standard logical operations.
  • Like relational operators, logical operators return Boolean values (i.e., they form Boolean expressions).

C++ logical operators

  • && (logical AND)
    • Takes two operands
    • Returns true if both operands are true, returns false otherwise.
  • || (logical OR)
    • Takes two operands
    • Returns true if either operand is true, returns false otherwise.
  • ! (logical NOT, logical negation)
    • Takes one operand
    • Returns true when its operand is false, false otherwise.
  • Precedence: !&&||

Truth table for logical AND

expression result
false && false false
false && true false
true && false false
true && true true

Truth table for logical OR

expression result
false || false false
false || true true
true || false true
true || true true

Truth table for logical NOT

expression result
!false true
!true false

Examples

assume: int x = 12, y = 5, z = -4;

expression result
(x > y) && (y > z) true
(x > y) && (z > y) false
(x <= z) || (y == z) false
(x <= z) || (y != z) true
!(x >= z)false

Short-circuiting

  • short-circuit evaluation: evaluating only as much as necessary (from left to right) to determine the result.
    int x = 5, y = 6;
    if ( (x < 0) && (-6 > y-1) )  // (-6 > y-1) is not evaluated
      ...
    if ( (x > 0) || (-6 > y-1) )  // (-6 > y-1) is not evaluated
      ...
  • Keep this in mind for later

More about Boolean values

  • In C++:
    • The value 0 (the integer zero) is considered false,
    • anything else is considered true.
  • Thus, the following example will print foo:
    if (6)
      cout << "foo" << endl;
    else
      cout << "bar" << endl;
  • and the following will print bar:
    if (0)
      cout << "foo" << endl;
    else
      cout << "bar" << endl;

Comparing characters and strings

switch structure

The conditional operator

  • C++ has a ternary conditional operator
    • Similar to an if/else control structure.
    • Unlike if/else, the conditional operator returns a value.
    • Syntax:expr1 ? expr2 : expr3;
    • Semantics: “If expr1 is true, return the value of expr2, otherwise return the value of expr3.”
    • Examples:
      y = x<0 ? -1.0*x : x;
      w = x<0 ? y=10 : z=20;

More about blocks and scope

  • See Gaddis 4.15 (programs Pr4-28.cpp to Pr4-30.cpp).
cplusplus/control_structures_selection.txt · Last modified: 2017/01/31 23:57 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki