DAT2322 - Course Notes

Introduction to Computer Programming

Prepared by Maitang Mark
March, 2000

Lesson 3

The Selection Control Structure (IF-THEN-ELSE)

    In this lesson, you will
  • learn about the selection control structure
  • learn about the conditional expression
  • learn about the relational operators
  • learn about the logical operators
  • learn about the nested if structure

Structured Programming

  The structured programming technique stipulates that all programs can be built using three basic control structures. They are:
Sequence
Selection
Iteration
All the Perl programs we learned so far are of sequential structure. When Perl executes the program, it starts at the top of the program and executes each statement in turn. When the final statement is executed, the program terminates.
    The Table of Contents
| To top |

The Selection Control Structure

  The selection control structure is used to make logical decisions. For example, if the number of hours worked includes overtime hours, you should be paid one and half of the regular hourly rate for the overtime hours.

The selection control structure is implemented by Perl in the following format:

    if ( a conditional expression )
            {
                    statements . . .
            }
    else
            {
                    statements . . .
            }
# The block of code to execute
# if the conditional expression results in true
 
 
# if the conditional expression results in true
# if the conditional expression results in false
The if statement starts with the keyword if, followed by a conditional expression. If the conditional expression is evaluated to be true, then the block of code enclosed in a pair of braces { } between if and else is to be executed. If the conditional expression is evaluated to be false, then the block of code after the else keyword is to be executed.

In the case that the conditional expression is false and nothing needs to be done, then the if statement can be simplified to become:

    if ( a conditional expression )
            {
                    statements . . .
            }

In an if statement, the conditional expression must be enclosed within a pair of brackets ( ). The statements to execute must be enclosed within a pair of braces { }. Even if you code an if statement which does nothing, you are required to include a pair of braces { }. For example:

    if ( $number1 > $number2 )
            { }

| To top |

The Conditional Expression

  A typical conditional expression uses the following operators

    Relational operator
            ==
            !=
            >
            <
            >=
            <=
Description
    equal to
    not equal to
    greater than
    less than
    greater than and equal to
    less than and equal to
    Logical operator      
            &&
            ||
            !
Description
    and
    or
    not
| To top |

Testing the positive number

  Program 3.1 Testing the positive number

This program accepts a number from the keyboard and displays it if it is a positive number.

# positive.pl	Positive number testing program
#
    print " Please enter a positive number: ";	# prompt for a number
    $number = <>;				# accept a number
    chomp($number);				# drop the Enter key
    if ( $number > 0 )				# test if the number is > 0
	{
	    print " It is a positive number. ";
	}
The above program tests the value entered if it is positive. If it is, then the program will display the following message, otherwise, nothing is printed.
    It is a positive number.
| To top |

A Grade Program

  Program 3.2 A Grade Program

This program accepts a grade and displays whether it is pass or fail.

# grade.pl	Determining a pass or fail grade
#
    print " Please enter a grade: ";		# prompt for a grade
    $grade = <>;				# accept a grade
    chomp($grade);				# drop the Enter key
    if   ( $grade >= 50)			# test if the grade >= 50
	{
	  print " You passed the test. ";	# The test is true,
	}					# print pass message
     else
	{
	  print " You failed the test. ";	# The test is false.
	}					# print fail message
If the conditional expression ($grade >= 50) is true, then the message " You passed the test. " is printed else the message " You failed the test. " is printed.
| To top |

Filling an Order Program

  Program 3.3 Filling an order Program

This program accepts an order and decides whether there are enough items in stock to fill the order.


# order.pl	Filling an order 
#
  $stockOnHand = 5;				  # assign a value to $stockOnHand
  print " Please enter an order quantity: ";	  # prompt for an order quantity
  $orderQuantity = <>;				  # accept the order quantity
  chomp($orderQuantity);			  # drop the Enter key 

  if   ( $orderQuantity > $stockOnHand)		  # test if there is enough in the stock
	{
	   print " Not enough stock to fill the order. ";   # can't fill the order
	}
  else
	{
	   print " Order processed ";		  # process the order	
	   $stockOnHand = $stockOnHand  - $orderQuantity;   # reduce the stock
	}
  print "\nThe stock on Hand is ", $stockOnHand;  # display stock on hand
						  # print fail message
 
The above program tests if the entered order quantity is greater than the stock on hand. If it is true, then it displays a message saying "Not enough stock to fill the order." else it displays the message " Order processed." and reduces the stock on hand. The if statement ends here. The last print statement prints the current value of $stockOnHand regardless of whether the order is processed or not because it is not a part of the if statement. The statement used to reduce the stock is:
  $stockOnHand = $stockOnHand - $orderQuantity;
When Perl executes this statement, the value of the $stockOnHand to the right of the assignment operator (=) is evaluated first, which is 5. The value 5 is used to complete the arithmetic expression:
  $stockOnHand - $orderQuantity;
The result of the subtraction is then assigned back to the variable $stockOnHand. This is a two-stage statement which is common among all the programming languages. The $stockOnHand at the right contains the initial value. The $stockOnHand at left ends up with the newly calculated value.

Is it possible for $stockOnHand to end up with a negative value in this program?

| To top |

A Payroll Program

  Program 3.4 A Payroll Program

# payroll.pl	Calculate Overtime Pay 
#
  $regularPay = 300;				# assign $300 to regular pay
  $rate=10;					# assign $10 to hourly rate
  print " Please enter overtime hours: ";	# prompt for overtime hours
  $overtimeHours = <>;				# accept overtime hours
  chomp($overtimeHours);			# drop the Enter key 

  if    ( $overtimeHours > 0)			# if there is overtime hours
	{
         $overtimePay = $overtimeHours * 1.5 * $rate;
         $regularPay = $regularPay + $overtimePay;
	}
  print " The pay this week is ", $regularPay;  # print the final pay
The above program tests to see if the employee worked overtime. If yes, the entered overtime hours are used to calculate the overtime pay at the one and half the regular rate. The overtime pay is also added to the regular pay. Notice again the statement:
  $regularPay = $regularPay + $overtimePay;
is again a two-stage statement in evaluating the variable $regularPay. The $regularPay at the right is to contain the initial value 300. The result of the addition:
  $regularPay + $overtimePay;
is assigned back to the $regularPay.
| To top |

A Guessing Game Program

 

Program 3.5. A Guessing Game Program

An arbitrary number is set for the user to guess.

# guess.pl	Guess a right number Program 
#
  $numberToGuess = 8;			# assign a number to guess
  print " Please guess a number between 1 and 10: ";	
					# prompt for a number
  $number = <>;				# accept the number
  chomp($number);			# drop the Enter key 

# if the number is equal to $numberToGuess
  if    ( $number == $numberToGuess)	
	 {
	   print " You guessed right.";
	 }
  else
	 {
	   print " You guessed wrong.";
	 }
The above program demonstrates the equal test condition using the equal comparison operator (==). It is commonly mixed up with the assignment operator (=).

The if ( $number == $numberToGuess) will match the values of the two variables and result in a true if they are equal and a false if they are not equal. After the expression is evaluated, both variables retain their original values.

The if ( $number = $numberToGuess) will assign the value of the variable $numberToGuess to the $number. This assignment expression yields a value which is the same as the value assigned to $number. After the expression is evaluated, the original value in $number is changed to that of $numberToGuess. This will cause your program to produce unpredictable results. If the value of $number is zero, then it is false. If it is a non-zero value, then it is true.

What if the user enters 9 which is out of the range between 1 and 8? It is a good practice to weed out the invalid responses and allow only the responses within the valid range to go through the process. The following program illustrates how the range check is done.

An Improved Guessing Game Program

 

Program 3.6. An Improved Guessing Game Program

This program validates the input value in the right range before going through the process.

# guess2.pl	Guess a right number Program with range check
#
  $numberToGuess = 8;			# assign a number to guess
  print " Please guess a number between 1 and 10: ";	
					# prompt for a number
  $number = <>;				# accept the number
  chomp($number);			# drop the Enter key 

  if ( $number < 1 || $number > 10 )	# weed out the invalid numbers
     {
	print " The number is out of the range (1-10). Try again."
     }
  else
     {					# process only valid numbers 
	if    ( $number == $numberToGuess)	
	 {
	   print " You guessed right.";
	 }
  	else
	 {
	   print " You guessed wrong.";
	 }
     }
| To top |

The Nested IF Structure

  Let's go back to Program 3-1, Testing the positive number. A number can be positive, negative, or zero. The if structure we learned so far can only test true or false, therefore, it is called two-way branching. How can we achieve a three-way branching? We need nested if structures. The following program places an if statement in the false block of another if statement to achieve a three-way branching.
 

Program 3.7 Testing a number to be positve, zero, or negative

The example illustrates that a three-way test requires a nested if statement.

# posneg.pl	Positive, zero, and negative testing program
#
   print " Please enter a number: ";		# prompt for a number
   $number = <>;				# accept a number
   chomp($number);				# drop the Enter key
   if ( $number > 0 )				# test if the number is > 0
	{
	  print " It is a positive number. ";
	}
   else
	{
	  if   ( $number == 0)			# test if the number is 0
	   { 
		print "It is a zero.";
	   }
	  else
	   {					# what is left is "<0" case
		print " It is a negative number. ";
	   }
	 }
In a multi-way branching case, it is important to match the braces for each block present. Missing one of the braces can easily turn into a debugging nightmare.
| To top |

Lesson 3 Exercises

 
  1. Write a program which will prompt for two numbers and display the one whose value is higher. Call it max.pl.

  2. Write a program which will prompt for two numbers and display the one whose value is lower. Call it min.pl.

  3. Write a program which will prompt for three numbers and display the one whose value is the highest among the three. Call it max3.pl. You will need to use a nested if statement.

  4. Write a program which will prompt for three numbers and display the one whose value is the lowest among the three. Call it min3.pl. You will need to use a nested if statement.

  5. Modify the sample program 3.5 guess.pl so that if the number gussed by the user is greater than the value to guess, then display "Too high". If it is lower than the number to guess, then display "Too low".

  6. Write a temperature conversion program which will first prompt for the types of conversion as below:
    		1. Converting Celsius to Fahrenheit.
    		2. Converting Fahrenheit to Celsius.
    
    		Select 1 or 2: 
    
    It then prompts for a temperature in number. Convert it accordingly. This problem combines both Exercises 2.5 and 2.6. Use an if statement to decide which way to convert. Call it temp3.pl.

  7. Write a measurement conversion program which will first prompt for the types of conversion as below:
    		1. Converting miles to kilometers.
    		2. converting kilometers to miles.
    
    		Select 1 or 2:
    
    It then prompts for a measurement in numbers. Convert it accordingly. This problem extends Program example 2.7 of Lesson 2. Use an if statement to decide which way to convert. Call it convert3.pl.
| To top |
M.  Mark, 2002.03.18 | Introduction | Lesson 1 | Lesson 2 | Lesson 3 | Lesson 4 | Appendix |