Two-Way Selection Statements

  • provides the means of choosing between two or more paths of execution

  • General Form:

    1
    2
    3
    4
    if control-expression
    // then-clause
    else
    // else-clause
    • the control expression must be Boolean in most of the languages
    • some other languages like C accepts numeric
  • Clause Form:

    • the then-clause and else-clause can be signle statement or compound statements in most of the languages
    • Perl only accepts compound statements
    • Python and Ruby: clauses are statement sequences

Nesting Selectors

  • Dangling else problem

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    bool condition1 = true;
    bool condition2 = false;
    string result = "haha";

    if(condition1)
    if(condition2)
    result = "hehe";
    else
    result = "hoho";

    cout << result << endl; // hoho
    • In C/C++/Java, else matches with the nearest previous if
  • In Perl, this is actually enforced

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    $condition1 = true;
    $condition2 = false;
    $result = "haha";

    if($condition1)
    {
    if($condition2)
    {
    $result = "hehe";
    } }
    else
    {
    $result = "hoho";
    }

    print $result;
  • In some languages, clauses are statement sequences which are ended by a reserved word end

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    condition1 = true
    condition2 = false
    result = "haha"

    if condition1 then
    if condition2 then
    result = "hehe"
    end
    else
    result = "hoho"
    end

    print(result)
  • In Python,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    condition1 = True
    condition2 = False
    result = "haha"

    if condition1:
    if condition2:
    result = "hehe"
    else:
    result = "hoho"

    print(result)

Multiple-Way Selection

  • allow the selection of one of any number of statements or statement groups

  • Switch statement in C, C++, and Java

    • Control expression and case constants can only be integers
    • default clause is for unrepresented values

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      switch (expression) {
      case const_expr_1:
      statement_1;
      break;
      ...
      case const_expr_n:
      statement_n;
      break;
      default:
      statement_n+1;
      }
    • Placement

      • switch-case has no restructions on the placement of the case expression
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        int x = 37;
        switch(x)
        default:
        if(isPrime(x)) // skip the if statement
        case 2: case 3: case 5: case 7: // quick jump
        processPrime(x);
        else
        case 4: case 6: case 8: case 9: case 10:
        processComposite(x);

  • unconditional branch in C#
    • C# allows unconditional branch like goto and break
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      int value = 0;
      int result = 0;
      switch(value){
      case < 0:
      result += 3;
      break;
      case 0:
      result += 5;
      goto case 1;
      case 1:
      result += 7;
      break;
      default:
      }
  • Multiple Selector in two-way selectors:

    • the connection of two-way selections using else if
      1
      2
      3
      4
      5
      6
      7
      8
      int n = 1;
      if(n == 1){
      cout << "one" << endl;
      }else if(n == 2){
      cout << "two" << endl;
      }else if(n == 3){
      cout << "three" << endl;
      }
    • but the structure is more look like this (which is not an actual multiple-way selection)

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      int n = 1;
      if(n == 1){
      cout << "one" << endl;
      }else{
      if(n == 2){
      cout << "two" << endl;
      }else{
      if(n == 3){
      cout << "three" << endl;
      }
      }
      }
    • In Python, elif is a single special keyword and enables actual multiple-way selection

      1
      2
      3
      4
      5
      6
      7
      n = 1
      if n == 1:
      print("one")
      elif n == 2:
      print("two")
      elif n == 3:
      print("three")
  • Implementation
    • General approach
      • multiple conditional branches
      • linear search of a simple table of case values
    • Optimized approaches
      • array
      • hash table

Counter-Controlled Loops

  • has a loop variable, and a means of specifying the initial, condition, and step
  • C-based language Syntax: for ([initial] ; [condition] ; [step]) body

    • the [initial], [condition] and [step] can be whole statements or even statement sequences(statement seperated by ,)

      1
      2
      3
      for (int i = 0, j = 0; i < 10; i++, j += 2){
      cout << "loop " << i << ", " << j << endl;
      }
    • It can even has no statements

      1
      2
      3
      4
      5
      6
      for (;;){   // while(true)
      // body
      }
      for (;A;){ // while(A)
      // body
      }
    • It is legal for C++ to go back to the loop body using goto

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      int i = 0;
      for (; i < 10; i++) {
      print:
      cout << "loop " << i << endl;
      }
      cout << "one more time?" << endl;
      char input;
      cin >> input;
      if (input == 'y') {
      goto print;
      }

Logic-Driven Loops

  • the repetition control is based on a Boolean expression

  • Pretest Loop

    • check the loop condition before the first iteration
    • while loop
      1
      2
      3
      while (control_expression) {
      // ...
      }
  • Posttest Loop

    • check the loop condition after the first iteration
    • do-while loop
      1
      2
      3
      do {
      // ...
      } while (control_expression)
  • It is also legal for C++ to go back to the loop body using goto

Data-Structure-Based Loops

  • the number of elements in a data structure controls loop iteration
  • call to an iterator function or a callable object that returns the next element in some chosen order, if there is one; else loop is terminated

  • Implement using pointer in C

    1
    2
    3
    for (node* p=root; p!=NULL; traverse(p)){
    // use *p to access the current element
    }
  • Standard Template Library in C++

    • instead of dealing with pointer, STL iterators can simply using the deference operator * and increment operators ++
      1
      2
      3
      for (vector<int>::iterator p=v.begin(); p!=v.end(); p++) {
      // use *p to access the current element
      }
  • Java Implementation

    • the class that implements the Iterable interface (ArrayList)

      1
      2
      3
      for (String myElement : myList){
      // ...
      }
    • forEach method

      1
      2
      3
      myList.forEach((n) -> {
      // ...
      });
  • Python Implementation

    • The loop variable takes on the values specified in the given sequence

      1
      2
      for loop_variable in sequence:
      # loop_body
    • else clause is execute if the loop terminates normally

      1
      2
      3
      4
      5
      6
      7
      8
      9
      pets = ["kitty", "doggy", "pig"]

      for pet in pets:
      if pet == "piggy":
      print("piggy is found!")
      break

      else: # if the loop terminates normally
      print("no piggy")
    • similate counter-controlled loop

      1
      2
      for i in range(10):
      print(i)

User-Located Loop Control Mechanisms

  1. unconditional unlabeled exits (break in most of the languages, last in Perl)

    • exit the loop
  2. unlabeled control statement (continue)

    • skips the the remainder of the current iteration, but does not exit the loop
  3. Labeled exits

    • consider the break can only exist for the current loop but cannot exit the outer loop
    • we can label the outer loop and then use break label; to exit the outer loop
      1
      2
      3
      4
      5
      6
      7
      8
      9
      outerLoop:
      for(int i = 0; i < 5; i++){
      for(int j = 0; j < 5; j++){
      if(i + j == 5){
      System.out.println(i + " " + j);
      break outerLoop;
      }
      }
      }
    • If goto is legal, then simply use goto to exit the outer loop