In many problems the value of a variable or the result of an expression can define which statement or block of statements should be executed. In the exercises that follow, you will learn how to test if a value or the result of an expression belongs within a specific range of values (from a series of consecutive ranges of values).

Suppose that you want to display a message indicating the types of clothes a woman might wear at different temperatures.

Outdoor Temperature

(in degrees Fahrenheit)

Types of Clothes a Woman Might Wear
Temperature < 45 Sweater, coat, jeans, shirt, shoes
45 ≤ Temperature < 65 Sweater, jeans, jacket, shoes
65 ≤ Temperature < 75 Capris, shorts, t-shirt, tank top, flip flops, athletic shoes
75 ≤ Temperature Shorts, t-shirt, tank top, skort, skirt, flip flops

At first glance you might be tempted to use single-alternative decision structures. It is not wrong actually but if you take a closer look, it becomes clear that each condition is interdependent, which means that when one of these evaluates to true, none of the others should be evaluated. You need to select just one alternative from a set of possibilities.

There are actually two decision control structures that can be used for this purpose, and these are the multiple-alternative decision structure and nested decision control structures. However, the multiple-alternative decision structure is the best choice. It is more convenient and increases readability.

Exercise – Calculating the Discount

Write a program that calculates the discount that customers receive based on the dollar amount of their order. If the total amount ordered is less than $30, no discount is given. If the total amount is equal to or greater than $30 and less than $70, a discount of 5% is given. If the total amount is equal to or greater than $70 and less than $150, a discount of 10% is given. If the total amount is $150 or more, the customer receives a discount of 20%.

Solution

The following table summarizes the various discounts that are offered.

Range Discount
amount < $30 0%
$30 ≤ amount < $70 5%
$70 ≤ amount < $150 10%
$150 ≤ amount 20%

The program is as follows.

PHP

<?php
  echo "Enter total amount: ";
  $amount = trim(fgets(STDIN));

  if ($amount < 30) {
    $discount = 0;
  }
  elseif ($amount >= 30 && $amount < 70) {
    $discount = 5;
  }
  elseif ($amount >= 70 && $amount < 150) {
    $discount = 10;
  }
  elseif ($amount >= 150) {
    $discount = 20;
  }

  $payment = $amount - $amount * $discount / 100;
  
  echo "You got a discount of ", $discount, "%\n";
  echo "You must pay $", $payment;
?>

Java

public static void main(String[] args) throws java.io.IOException {
  java.io.BufferedReader cin = new java.io.
          BufferedReader(new java.io.InputStreamReader(System.in));
  double amount, discount, payment;

  System.out.print("Enter total amount: ");
  amount = Double.parseDouble(cin.readLine());

  if (amount < 30) {
    discount = 0;
  }
  else if (amount >= 30 && amount < 70) {
    discount = 5;
  }
  else if (amount >= 70 && amount < 150) {
    discount = 10;
  }
  else if (amount >= 150) {
    discount = 20;
  }

  payment = amount - amount * discount / 100;
  
  System.out.println("You got a discount of " + discount + "%");
  System.out.println("You must pay $" + payment);
}

C++

#include <iostream>
using namespace std;
int main() {
  double amount, discount, payment;

  cout << "Enter total amount: ";
  cin >> amount;

  if (amount < 30) {
    discount = 0;
  }
  else if (amount >= 30 && amount < 70) {
    discount = 5;
  }
  else if (amount >= 70 && amount < 150) {
    discount = 10;
  }
  else if (amount >= 150) {
    discount = 20;
  }

  payment = amount - amount * discount / 100;
  
  cout << "You got a discount of " << discount << "%" << endl;
  cout << "You must pay $" << payment;
  return 0;
}

C#

static void Main() {
  double amount, discount = 0, payment;

  Console.Write("Enter total amount: ");
  amount = Double.Parse(Console.ReadLine());

  if (amount < 30) {
    discount = 0;
  }
  else if (amount >= 30 && amount < 70) {
    discount = 5;
  }
  else if (amount >= 70 && amount < 150) {
    discount = 10;
  }
  else if (amount >= 150) {
    discount = 20;
  }

  payment = amount - amount * discount / 100;
  
  Console.WriteLine("You got a discount of " + discount + "%");
  Console.Write("You must pay $" + payment);
  Console.ReadKey();
}

Visual Basic

Sub Main()
  Dim amount, discount, payment As Double

  Console.Write("Enter total amount: ")
  amount = Console.ReadLine()

  If amount < 30 Then
    discount = 0
  ElseIf amount >= 30 And amount < 70 Then
    discount = 5
  ElseIf amount >= 70 And amount < 150 Then
    discount = 10
  ElseIf amount >= 150 Then
    discount = 20
  End If

  payment = amount - amount * discount / 100

  Console.WriteLine("You got a discount of " & discount & "%")
  Console.Write("You must pay $" & payment)

  Console.ReadKey()
End Sub

Python

amount = float(input("Enter total amount: "))

if amount < 30:
    discount = 0
elif amount >= 30 and amount < 70:
    discount = 5
elif amount >= 70 and amount < 150:
    discount = 10
elif amount >= 150:
    discount = 20

payment = amount - amount * discount / 100

print("You got a discount of ", discount, "%", sep = "")
print("You must pay $", payment, sep = "")

A closer examination, however, reveals that the Boolean expressions (written in the marked lines) can be further improved. For example, when the first Boolean expression evaluates to false, the flow of execution continues to evaluate the second Boolean expression, in which, variable amount is definitely greater than or equal to 30. Therefore, the Boolean expression amount >= 30, when evaluated, is certainly true and thus can be omitted. The same logic applies to all cases; you can improve all Boolean expressions written in the marked lines. The final program is shown here, with all unnecessary evaluations removed.

PHP

<?php
  echo "Enter total amount: ";
  $amount = trim(fgets(STDIN));

  if ($amount < 30) {
    $discount = 0;
  }
  elseif ($amount < 70) {
    $discount = 5;
  }
  elseif ($amount < 150) {
    $discount = 10;
  }
  else {
    $discount = 20;
  }

  $payment = $amount - $amount * $discount / 100;
  
  echo "You got a discount of ", $discount, "%\n";
  echo "You must pay $", $payment;
?>

Java

public static void main(String[] args) throws java.io.IOException {
  java.io.BufferedReader cin = new java.io.
          BufferedReader(new java.io.InputStreamReader(System.in));
  double amount, discount = 0, payment;

  System.out.print("Enter total amount: ");
  amount = Double.parseDouble(cin.readLine());

  discount = 0;

  if (amount < 30) {
    discount = 0;
  }
  else if (amount < 70) {
    discount = 5;
  }
  else if (amount < 150) {
    discount = 10;
  }
  else {
    discount = 20;
  }

  payment = amount - amount * discount / 100;
  
  System.out.println("You got a discount of " + discount + "%");
  System.out.println("You must pay $" + payment);
}

C++

#include <iostream>
using namespace std;
int main() {
  double amount, discount, payment;

  cout << "Enter total amount: ";
  cin >> amount;

  if (amount < 30) {
    discount = 0;
  }
  else if (amount < 70) {
    discount = 5;
  }
  else if (amount < 150) {
    discount = 10;
  }
  else {
    discount = 20;
  }

  payment = amount - amount * discount / 100;
  
  cout << "You got a discount of " << discount << "%" << endl;
  cout << "You must pay $" << payment;
  return 0;
}

C#

static void Main() {
  double amount, discount, payment;

  Console.Write("Enter total amount: ");
  amount = Double.Parse(Console.ReadLine());

  if (amount < 30) {
    discount = 0;
  }
  else if (amount < 70) {
    discount = 5;
  }
  else if (amount < 150) {
    discount = 10;
  }
  else {
    discount = 20;
  }

  payment = amount - amount * discount / 100;
  
  Console.WriteLine("You got a discount of " + discount + "%");
  Console.Write("You must pay $" + payment);
  Console.ReadKey();
}

Visual Basic

Sub Main()
  Dim amount, discount, payment As Double

  Console.Write("Enter total amount: ")
  amount = Console.ReadLine()

  If amount < 30 Then
    discount = 0
  ElseIf amount < 70 Then
    discount = 5
  ElseIf amount < 150 Then
    discount = 10
  Else
    discount = 20
  End If

  payment = amount - amount * discount / 100

  Console.WriteLine("You got a discount of " & discount & "%")
  Console.Write("You must pay $" & payment)

  Console.ReadKey()
End Sub

Python

amount = float(input("Enter total amount: "))

if amount < 30:
    discount = 0
elif amount < 70:
    discount = 5
elif amount < 150:
    discount = 10
else:
    discount = 20

payment = amount - amount * discount / 100

print("You got a discount of ", discount, "%", sep = "")
print("You must pay $", payment, sep = "")
Exercise – Validating Data Input and Calculating the Discount

Rewrite the program of the previous exercise to validate the data input. Individual error messages should be displayed when the user enters any non-numeric or negative values.

Solution

Let’s try once again the “from inner to outer” method. The inner code fragment has already been discussed in the previous exercise, whereas the outer program that validates data input is shown here.

PHP

<?php
  echo "Enter total amount: ";
  $amount = trim(fgets(STDIN));

  if (is_numeric($amount) != true) {
    echo "Entered value contains non-numeric characters";
  }
  elseif ($amount < 0) {
    echo "Entered value is negative";
  }
  else {
    //Here goes the code that calculates
    //and displays the discount offered
  }
?>

Java

static final String IS_NUMERIC = "[-+]?\\d+(\\.\\d+)?";

public static void main(String[] args) throws java.io.IOException {
  java.io.BufferedReader cin = new java.io.
          BufferedReader(new java.io.InputStreamReader(System.in));
  double amount, discount, payment;
  String amount_str;

  System.out.print("Enter total amount: ");
  amount_str = cin.readLine();

  if (amount_str.matches(IS_NUMERIC) != true) {
    System.out.println("Entered value contains non-numeric characters");
  }
  else {
    amount = Double.parseDouble(amount_str);
    if (amount < 0) {
      System.out.println("Entered value is negative");
    }
    else {
      //Here goes the code that calculates
      //and displays the discount offered
    }
  }
}

C++

#include <iostream>
using namespace std;

int main() {
  double amount, discount, payment;

  cout << "Enter total amount: ";
  cin >> amount;

  if (cin.fail() == true) {
    cout << "Entered value contains non-numeric characters" << endl;
    cin.clear();
    cin.ingore(100, '\n');
  }
  else if (amount < 0) {
    cout << "Entered value is negative" << endl;
  }
  else {
    //Here goes the code that calculates
    //and displays the discount offered
  }
  return 0;
}

C#

static void Main() {
  double amount, discount, payment;
  string input;

  Console.Write("Enter total amount: ");
  input = Console.ReadLine();

  if (Double.TryParse(input, out amount) == false) {
    Console.WriteLine("Entered value contains non-numeric characters");
  }
  else if (amount < 0) {
    Console.WriteLine("Entered value is negative");
  }
  else {
    //Here goes the code that calculates
    //and displays the discount offered
  }
  Console.ReadKey();
}

Visual Basic

Sub Main()
  Dim amount, discount, payment As Double
  Dim input As String

  Console.Write("Enter total amount: ")
  input = Console.ReadLine()

  If Double.TryParse(input, amount) = False Then
    Console.WriteLine("Entered value contains non-numeric characters")
  ElseIf amount < 0 Then
    Console.WriteLine("Entered value is negative")
  Else
    'Here goes the code that calculates
    'and displays the discount offered
  End If

  Console.ReadKey()
End Sub

Python

import re
IS_NUMERIC = "^[-+]?\\d+(\\.\\d+)?$"

inp = input("Enter total amount: ")

if not re.match(IS_NUMERIC, inp):
    print("Entered value contains non-numeric characters")
else:
    amount = float(inp)
    if amount < 0:
        print("Entered value is negative")
    else:
        #Here goes the code that calculates
        #and displays the discount offered

Combining this with the program of the previous exercise, the final program becomes

PHP

<?php
  echo "Enter total amount: ";
  $amount = trim(fgets(STDIN));

  if (is_numeric($amount) != true) {
    echo "Entered value contains non-numeric characters";
  }
  elseif ($amount < 0) {
    echo "Entered value is negative";
  }
  else {
    if ($amount < 30) {
      $discount = 0;
    }
    elseif ($amount < 70) {
      $discount = 5;
    }
    elseif ($amount < 150) {
      $discount = 10;
    }
    else {
      $discount = 20;
    }

    $payment = $amount - $amount * $discount / 100; 

    echo "You got a discount of ", $discount, "%\n";
    echo "You must pay $", $payment;
  }
?>

Java

static final String IS_NUMERIC = "[-+]?\\d+(\\.\\d+)?";

public static void main(String[] args) throws java.io.IOException {
  java.io.BufferedReader cin = new java.io.
          BufferedReader(new java.io.InputStreamReader(System.in));
  double amount, discount, payment;
  String amount_str;

  System.out.print("Enter total amount: ");
  amount_str = cin.readLine();

  if (amount_str.matches(IS_NUMERIC) != true) {
    System.out.println("Entered value contains non-numeric characters");
  }
  else {
    amount = Double.parseDouble(amount_str);
    if (amount < 0) {
      System.out.println("Entered value is negative");
    }
    else {
      discount = 0;

      if (amount < 30) {
        discount = 0;
      }
      else if (amount < 70) {
        discount = 5;
      }
      else if (amount < 150) {
        discount = 10;
      }
      else {
        discount = 20;
      }
      payment = amount - amount * discount / 100; 
    
      System.out.println("You got a discount of " + discount + "%");
      System.out.println("You must pay $" + payment);
    }
  }
}

C++

#include <iostream>
using namespace std;

int main() {
  double amount, discount, payment;

  cout << "Enter total amount: ";
  cin >> amount;

  if (cin.fail() == true) {
    cout << "Entered value contains non-numeric characters" << endl;
    cin.clear();
    cin.ignore(100, '\n');
  }
  else if (amount < 0) {
    cout << "Entered value is negative" << endl;
  }
  else {
    if (amount < 30) {
      discount = 0;
    }
    else if (amount < 70) {
      discount = 5;
    }
    else if (amount < 150) {
      discount = 10;
    }
    else {
      discount = 20;
    }
    payment = amount - amount * discount / 100; 
  
    cout << "You got a discount of " << discount << "%" << endl;
    cout << "You must pay $" << payment << endl;
  }
  return 0;
}

C#

static void Main() {
  double amount, discount, payment;
  string input;

  Console.Write("Enter total amount: ");
  input = Console.ReadLine();

  if (Double.TryParse(input, out amount) == false) {
    Console.WriteLine("Entered value contains non-numeric characters");
  }
  else if (amount < 0) {
    Console.WriteLine("Entered value is negative");
  }
  else {
    if (amount < 30) {
      discount = 0;
    }
    else if (amount < 70) {
      discount = 5;
    }
    else if (amount < 150) {
      discount = 10;
    }
    else {
      discount = 20;
    }
    payment = amount - amount * discount / 100; 
  
    Console.WriteLine("You got a discount of " + discount + "%");
    Console.WriteLine("You must pay $" + payment);
  }
  Console.ReadKey();
}

Visual Basic

Sub Main()
  Dim amount, discount, payment As Double
  Dim input As String

  Console.Write("Enter total amount: ")
  input = Console.ReadLine()

  If Double.TryParse(input, amount) = False Then
    Console.WriteLine("Entered value contains non-numeric characters")
  ElseIf amount < 0 Then
    Console.WriteLine("Entered value is negative")
  Else
    If amount < 30 Then
      discount = 0
    ElseIf amount < 70 Then
      discount = 5
    ElseIf amount < 150 Then
      discount = 10
    Else
      discount = 20
    End If
    payment = amount - amount * discount / 100

    Console.WriteLine("You got a discount of " & discount & "%")
    Console.WriteLine("You must pay $" & payment)
  End If

  Console.ReadKey()
End Sub

Python

import re
IS_NUMERIC = "^[-+]?\\d+(\\.\\d+)?$"

inp = input("Enter total amount: ")

if not re.match(IS_NUMERIC, inp):
    print("Entered value contains non-numeric characters")
else:
    amount = float(inp)
    if amount < 0:
        print("Entered value is negative")
    else:
        if amount < 30:
            discount = 0
        elif amount < 70:
            discount = 5
        elif amount < 150:
            discount = 10
        else:
            discount = 20
        payment = amount - amount * discount / 100

        print("You got a discount of ", discount, "%", sep = "")
        print("You must pay $", payment, sep = "")

Notice: The marked lines are from the previous exercise