DAT2322 - Course Notes

Introduction to Computer Programming

Prepared by Maitang Mark
March, 2000

Lesson 2

Arithmetic Operations and the Input Function

    In this lesson, you will
  • learn about arithmetic operations
  • learn about arithmetic expressions and assignment expressions
  • learn about how Perl accepts values from the keyboard
  • learn about the chomp() function

Arithmetic Operations

    Computers are very efficient with performing arithmetic operations.
    Perl recognizes the following arithmetic operators:

            Operation             Operator
            Addition                     +
            Subtraction                 -
            Multiplication             *
            Division                       /

    These operators can be used the same way as you do arithmetic
    on paper. For example


  $sum = 3 + 4;
    The Table of Contents
  The above statement adds 3 and 4 and then assigns the result, 7, to the variable $sum. The numbers 3 and 4 are operands. They are operated on by the addition (+) operator.

It is possible to perform more than one arithmetic operation in a single statement. For example:


 $net = 6 + 12  - 3;
  Save the arithmetic
    results in variables.
    for later use.
 

The above two statements deal with numeric constants. Arithmetic operations can be performed on numeric variables as well. For example:


$cost = 6;
$total = $cost * 3;	# Three items were sold.

The second statement takes the value currently stored in $cost, 6, and multiplies it by 3. The result, 18, is assigned to the variable $total.

  You can do
    arithmetic
    on variables.
| To top |

A simple addition program

 

Program 2.1 A simple addition program

This program sets up three variables. Two are for storing numbers. The third one is for storing their sum.

#   add.pl	An adding program			# line 1
#							# line 2
      $number1 = 3;					# line 3
      $number2 = 4;					# line 4
      $sum = $number1 + $number2;			# line 5
       print $number1, " + ", $number2, " = ", $sum;	# line 6
The result after executing the above program is:
    3 + 4 = 7    
  The above program demonstrates several new features. The first two lines are comment lines. They are not executable. Perl ignores all words after the pound sign #. On line 3, note that the symbol # appears after the assignment instruction. Again Perl ignores the words after #. You can put comments on the same line as the regular instruction provided that you place a pound sign # before the comments.

The numeric values 3 and 4 are assigned to variables $number1 and $number2 on lines 3 and 4. On line 5, they are added and their sum is assigned to the variable $sum. On line 6, the print command prints the five data items on the display screen.

The assignment instruction on line 5 has the format :

variable = arithmetic expression

where $sum is the variable to the left of the assignment operator (=). At the right side $number1 + $number2 is an arithmetic expression. The result of the addition is assigned to $sum

Perl will do its best to convert a string into a number if you place a variable with a string value in an arithmetic expression. String "3TO4" is considered having a numeric value of 3. String "TO4" is considered zero.

  Comments can be placed
    with an instruction
    on the same line.

    Change line 3 of Program 2-1 to read

#   add.pl	An adding program			# line 1
#							# line 2
      $number1 = "3";					# line 3
      $number2 = 4;					# line 4
      $sum = $number1 + $number2;			# line 5
       print $number1, " + ", $number2, " = ", $sum;	# line 6
    Save and run the program again, you will have the same result:
3 + 4 = 7
  It is because "3" + 4 is equivalent to 3 + 4 and results in 7. If line 3 were $number1 = "A" which is treated as zero, the result would be 4. Perl will try its best to give you an arithmetic result even if we supply invalid values in an arithmetic expression.
| To top |

A simple multiplication program

 

Program 2.2 A simple multiplication program


#   multiply.pl	A multiplication  program	
#
      $cost = 6;	
      $quantity = 4;
      $total = $cost * $quantity;
       print $cost, " times ", $quantity, " equals ", $total;
The result after executing the above program is:
6 times 4 equals 24
At the time the print instruction is executed, the value in $cost is 6, the value in $quantity is 4,
and the value in $total is 24.
| To top |

A multiple operation program

  An arithmetic expression may contain more than one operation.

Program 2.3 An arithmetic operation with more than one arithmetic operator


#   two-op.pl	Two operation arithmetic
#
      $cost = 6;	
      $tax = $cost * 0.15;
      $total = ($cost + $tax )* 4;
       print "Total cost plus tax is ", $total;
The result after executing the above program is:
Total cost plus tax is 27.6
| To top |

Operator Precedence

  Multiplication and division are always performed before addition and subtraction, like the way you do arithmetic on paper. Multiplication and division are said to have higher operator precedence over addition and subtraction. Among the operators of the same precedence, such as multiplication and division, or subtraction and addition, the order of operations is from left to right. If you wish to override the precedence rule, use parentheses.

  $total = $cost + $tax * 4;	# * is performed first
  $total = ($cost + $tax )* 4;	# + is performed first
The results of the above two statements are not the same. Since multiplication has higher precedence over addition, the multiplication operation is performed first in the first statement. In the second statement, the addition, which is enclosed in a pair of parentheses, is performed ahead of the multiplication. As an exercise, remove the parentheses from the arithmetic expression in Program 2-3, save, and run it to see the result.
If in doubt use
 parentheses.
| To top |

Converting miles to kilometers

 

Program 2.4 Converting miles to kilometers


# miletokm.pl		Miles to kilometer Conversion Program
#
    $miles = 100;
    $km = $miles * 1.6;
    print $miles, " miles is equivalent to ", $km, " kilometers. \n";
The result after executing the above program is:
100 miles is equivalent to 160 kilometers.
| To top |

Assignments and Expressions

  An assignment statement which contains an assignment operator (=) can assign a constant value,
a variable value, or the result of an expression to the variable at left.


$cost = 6; 		 # the numeric constant 6 is assigned to $cost
$netPrice = $cost;	 # the value of $cost is assigned to $netPrice
$total=($cost + $tax)*4; # the result of the expression is assigned to $total
  The third statement contains an arithmetic expression ($cost + $tax)*4. A statement and an expression are two different things. A statement, however, can contain an expression.

An expression always yields a result. There are many kinds of expressions. We have seen many examples of arithmetic expressions. There are also relational expressions, function expressions, etc.

  A statement is an
    instruction.
    An expression is a part
    of an instruction.
  Perl is similar to C, C++, and Java, in that the assignment statement is itself an expression. It is called the assignment expression. Each Perl assignment expression yields a result. The result of an assignment operation is the value assigned. For example:

   $cost = 6;
The result of the assignment expression is 6, which is the value assigned to $cost. Because the assignment operator yields a value, you can use more than one assignment operator in a single expression:

   $netPrice = $cost = 6;
In this example, the right portion of the statement
            $cost = 6
is performed first. The result of this subexpression is 6 and the expression is now
            $netPrice = 6
At this point, 6 is assigned to $netPrice.
  An assignment
    statement is itself
    an expresssion.
| To top |

The Keyboard Input Command

  Perl accepts input values from the keyboard with an assignment statement. Most other programming languages have a specific input command to perform this input function. For example, COBOL uses Accept, C uses scanf(), Basic uses get, etc. The keyboard input to Perl is the default method of inputting values. It is represented by <> which is the standard input buffer symbol. What is being keyed on the keyboard terminated by the Enter key, is placed in the standard input buffer <>. The assignment statement assigns the value in <> to a variable. For example:

  $name = <>;
Put it in the following hello2.pl program:
  The symbol <>
    represents the
    standard input buffer.
| To top |

A Personal Hello program

  Program 2-5 A personal hello program

# hello2.pl	This program asks for your name, then 
#		prints a hello message.
#
   print "What is your name?  ";
   $name = <>;
   print "Hello ", $name;
Save it as A:\hello2.pl.

Execute it in Perl's MS-DOS Window,
perl hello2.pl
It will first ask for your name:
What is your name?
You are expected to type your name following the question. For example,
Bob
It will then print the following line:
Hello Bob
  Run the program again. (You can press F3 to repeat the last DOS command.) This time, type a different name when prompted, for example: Max. See what the program will reply.

When a user can supply values to a program from the keyboard, the program will respond according to what the user keyed in. We can transform one of the previously static programs into a more responsive or lively program. For example Program 2-1 can be rewritten to:

  The keyboard input allows
    user-computer interaction.
| To top |

An Adding program

  Program 2.6 An adding program:     It prompts for two numbers and displays their sum.

Use a text editor to compose the following program:


#   add2.pl	An adding program
#
   print "Enter a number: ";			 # prompt for a number
   $number1 = <>;				 # accept a number
   print "Enter another number: ";		 # prompt for another number
   $number2 = <>;				 # accept the second number
   $sum = $number1 + $number2;		    	 # add these two numbers
   print $number1, " + ", $number2, " = ", $sum; # print the results
When you run the program and key 6 and 8 when prompted, the session goes like this:
  Enter a number: 6
  Enter another number: 8
  6
  + 8
  = 14
 

Our original intent is to print 6 + 8 = 14 on one line. Why is it printed on three lines? The reason is that when Perl assigned what was in the standard input buffer <> to the variables $number1, it took the terminating Enter key along too. The value stored in the $number1 was 6 and the invisible Enter key. When it was printed, the Enter key caused the next item " + " to drop to the next line. The same goes with 8, which was followed by an Enter key. Therefore, the next two items " =" and the value of $sum had to drop a line.

  The <> passes the Enter
    key to variables.
| To top |

The chomp() Function

  The chomp() function is devised to drop the last character of a variable provided the last character is an Enter key. If the last character of a variable is not an Enter key, then nothing is dropped. Now, let us revise the Program 2-6, An addition program, to read:

#   add2.pl	An adding program
#
   print "Enter a number: ";			 # prompt for a number
   $number1 = <>;				 # accept a number
   chomp($number1);				 # drop the Enter key
   print "Enter another number: ";		 # prompt for another number
   $number2 = <>;				 # accept the second number
   chomp($number2);				 # drop the Enter key
   $sum = $number1 + $number2;		    	 # add these two numbers
   print $number1, " + ", $number2, " = ", $sum; # print the results
When you run the program again and key 6 and 8 when prompted, the session goes like this:
Enter a number: 6 
Enter another number: 8
6 + 8 = 14 
Press F3 to run the program again. This time use 5 and 7. This program is made to add any two numbers of your choice.

As an exercise, modify Program 2-2, the multiplication program, so that it will multiply any two numbers of your choice.

| To top |

Converting miles to kilometers

  Program 2-7 Converting miles to kilometers with a user input routine.

# convmile.pl		Miles to kilometer Conversion Program
#
    print "Enter miles: ";	# prompt for miles
    $miles = <>;		# accept the user input
    chomp($miles);		# drop the Enter key
    $km = $miles * 1.6;		# convert it the kilometers
    print $miles, " miles is equivalent to ", $km, " kilometers. \n";
Run the program and key 50 when prompted. The session will look like this:
Enter miles: 50
50 miles is equivalent to 80 kilometers.
| To top |

Lesson 2 Exercises

 
  1. Write a multiplication program which will prompt for two numbers and display both numbers and their product in an arithmetic formula form (e.g., 2 * 3 = 6).

  2. Write a subtraction program which will prompt for two numbers and display both numbers and their difference in an arithmetic formula form.

  3. Write a payroll program which will prompt for an hourly rate and the number of hours worked. Calculate the gross_pay ( = hours times rate) and display it.

  4. Add to the payroll program above the tax deduction amount which is is calculated at 30% of the gross_pay. Calculate also the net_pay which is gross_pay less tax deduction. Display the results as follows:
    Hourly rate:
    Hours worked:
    Gross pay:
    tax deducted:
    Net pay:
  5. Write a temperature conversion program which will prompt for a Celsius temperature and conver it to a Fahrenheit degree. Display both. ( f = c *9 /5 + 32 )

  6. Write a temperature conversion program which will prompt for a Fahrenheit temperature and convert it to a Celsius degree. Display both.
| To top |
M. Mark, 2002.03.18 | Introduction | Lesson 1 | Lesson 2 | Lesson 3 | Lesson 4 | Appendix |