Decision Structures

Overview

Programmers have to understand the concept of choice. Given a set value or set of values, we need to design programs that offer choices. At an ATM we are presented with a menu of transaction options. The choice of a single option determines an entire sequence of operations. The programmers of the ATM have also programmed all the options presented in the ATM. Whatever the option, there is a direction of code.

Decision structures make branching happen. Also, this is one of the most uniform concept in all of programming. It must be understood that decision structures are a programming ideology. As you plan your program solution, rest assured that what you consider in one language works in many other languages as well. The keyword for decision structures in if. We will explore the variety of if statements that we can encounter in programming.

Relational Operators

Conditions either exist or they do not. In other words, the condition is either true or false. In programming there are 6 relational operators. When relational operators are used in expressions, the expression is called a relational expression. The results of a relational expression are always true or false. Here is a list of the relational operators.
>
e.g. x > y
Greater than: yields true if x has a numeric equivalent value that is higher than y and false otherwise.
>=
e.g. x >= y
Greater than or equal to: yields true if x is at least numerically equivalent to or higher than y and false otherwise.
<
e.g. x < y
Less than: yields true if x has a numeric equivalent value that is lower than y and false otherwise.
<=
e.g. x <= y
Less than or equal to: yields true if x is at least numerically equivalent to or lower than y and false otherwise.
==
e.g. x == y
Equal to: yields true if x has a numeric equivalent value that is the same as y and false otherwise.
!=
e.g. x != y
Not equal to: yields true if x has a numeric equivalent value that is not the same as y and false otherwise.

Single-Alternative Decision Structures

if statements

There are times where we want our program to respond only when a condition exists. Consider that we want to write a programming statement that asks the user for a grade and will respond with a message if the learner passed. Here are examples in the various languages.

*-not considering input validation at this stage
Pass notice
Language Code
C++ #include<iostream>
using namespace std;

int main(){
   int grade;
   cout << "Enter final score for the semester: ";
   cin >> score;

   if (grade >= 70) {
      cout << "You passed the class!" << endl;
   }
}
C# using System;
namespace GradeNotice {
 class GradeNoticeProgram {
  static void Main(string[] args) {
   int grade;
   Console.WriteLine("Enter final score for the semester: ");
   grade = int.Parse(Console.ReadLine());

   if (grade <= 70) {
    Console.WriteLine("You passed the class!");
   }

  }
 }
}
Java import java.util.Scanner;

public class GradeNotice {
 public static void main(String[] args) {
  Scanner keyIn = new Scannner(System.in);
  int grade;
  System.out.print("Enter final score for the semester: ");
  grade = keyIn.nextInt();
  if (grade <= 70) {
   System.out.println("You passed the class!");
  }

 }
}
Python grade = int(input("Enter final score for the semester: "))
if grade <= 70:
   print("You passed the class!")

For this program, there will be no output unless the user inputs an integer value 70 or greater. If the program example had more code above the if statement and below it, if the user entered a grade below 70, then the code would execute everything above and below the decision structure.

Single-alternative decision structures are called if-statments as well as "do this or do nothing statements."

Dual-Alternative Decision Structures

if-else statments

There are some times where a decision has to be made that is mutually exclusive. Consider a course where you either pass or you fail. There are no additional options but those two. When we arrive at this branch, one option must be chosen. This is the dual alternative decision structure. Let's look at coding examples of a pass-fail program.

*-not considering input validation at this stage
Pass-Fail Program
Language Code
C++ #include<iostream>
using namespace std;

int main(){
   int grade;
   cout << "Enter final score for the semester: ";
   cin >> score;

   if (grade >= 70) {
      cout << "You passed the class!" << endl;
   }
   else {
      cout << "You failed the class." << endl;
}
C# using System;
namespace GradeNotice {
 class GradeNoticeProgram {
  static void Main(string[] args) {
   int grade;
   Console.WriteLine("Enter final score for the semester: ");
   grade = int.Parse(Console.ReadLine());

   if (grade <= 70) {
    Console.WriteLine("You passed the class!");
   }
   else {
    Console.WriteLine("You failed the class.");    }

  }
 }
}
Java import java.util.Scanner;

public class GradeNotice {
 public static void main(String[] args) {
  Scanner keyIn = new Scannner(System.in);
  int grade;
  System.out.print("Enter final score for the semester: ");
  grade = keyIn.nextInt();
  if (grade <= 70) {
   System.out.println("You passed the class!");
  }
  else {
   System.out.println("You failed the class.");
  }

 }
}
Python grade = int(input("Enter final score for the semester: "))
if grade <= 70:
   print("You passed the class!")
else:
   print("You failed the class.")

This code is written so there will only be a message that the student passed the class or failed the class. There is no way to know what the output will be at run time until the end user inputs the grade value. Also, notice that else does not require an explicit condition because it is only activated if the if condition is false.

Multiple-Alternative Decision Structures

When we considered a menu-driven screen at the ATM, we should realize that the user will select only one of the options at any given time. If the user selects "Deposit" then the user did not select the other options on the screen. We would need to write a structure that would define a branch for each particular item. To play with the idea presented in single-alternative and dual-alternative descriptions, let's consider that the user (a student) wants to know his or her final grade. We can accomplish this using a multiple alernative statement (called if-else-if statements)

if-else-if statements

I know that I am staying fairly high-level in this introduction of coding. The if-else-if is a special construct known as a nested statement. What we are actually saying is this: if the first condition is true, execute the body of that if block, else, if the second condition is true, execute the second body, else, if the third condition is true... and so on.

There could be a possibility of all the conditions not being true for an execution and then the block will produce no output (just like an if statement). To prevent this from happening, programmers often use a "trailing else" to output a statement if none of the conditions are true.

Let's look at a letter grade output program where A ranges from 90 - 100, B ranges from 80 - 89, C, 70 - 79, D, 60 - 69, and F, 0 - 59.

LanguageCode
*not accounting for input validation
C++ #include <iostream>
using namespace std;

int main(){
  int grade;
  char letter;
  cout << "Enter final score for the class: ";
  cin >> grade;

  if (grade >= 90) {
    letter = 'A';
  }
  else if (grade >= 80) {
    letter = 'B';
  }
  else if (grade >= 70) {
    letter = 'C';
  }
  else if (grade >= 60) {
    letter = 'D';
  }
  else {
    letter = 'F'
  }
  cout << "Your final grade is " << letter << endl;
}
C# using System;
namespace Grades{
  class GradeBook{
    static void Main(string[] args){
      int grade;
      char letter;
      Console.WriteLine("Enter final score for the class: ");
      grade = int.Parse(Console.ReadLine());

      if (grade >= 90) {
        letter = 'A';
      }
      else if (grade >= 80) {
        letter = 'B';
      }
      else if (grade >= 70) {
        letter = 'C';
      }
      else if (grade >= 60) {
        letter = 'D';
      }
      else {
        letter = 'F'
      }
      Console.WriteLine($"Your final grade is {letter}");
    }
  }
}
Java import java.util.Scanner;

public class GradeBook{
  public static void main(String[] args){
    Scanner keyIn = new Scanner(System.in);
    int grade;
    char letter;
    System.out.print("Enter final score for the class: ");
    grade = keyIn.nextInt();

    if (grade >= 90) {
      letter = 'A';
    }
    else if (grade >= 80) {
      letter = 'B';
    }
    else if (grade >= 70) {
      letter = 'C';
    }
    else if (grade >= 60) {
      letter = 'D';
    }
    else {
      letter = 'F'
    }
    System.out.printf("Your final grade is %c%n", letter);
    keyIn.close();
  }
}
Python grade = int(input("Enter final score for the class: "))

if grade >= 90:
    letter = 'A'
elif grade >= 80:
    letter = 'B'
elif grade >= 70:
    letter = 'C'
elif grade >= 60:
    letter = 'D'
else:
    letter = 'F'
print("Your final grade is", letter)

Notice that the logic of this construct is built so that only one condition is true for the entire block. While 92 is greater than or equal to 80, 70, and 60, 92 would trigger the first block. If a condition is true, then there is no more decision to be made in the block. Also notice that a variable letter was used to capture the letter grade. This allows me to not have to write repetitive output statements just for each grade range.

Notice that in Python, the keyword of elif is used where else if is used by the others.

Summary

There are way more details that could have been addressed but these are the very high points of decision structures. We need them to allow our programs to provide real interactivity by giving the user his or her own experience with your program. As the programmer, it is important to define all the alternatives for decision structures. Knowing the right type of decision structure is beneficial for code design. It is also important to know that programmers have the abiliity to design conditions as loosely or as stringent as the algorithm requires.