First ... Back ... Next ... Last ... (Notes home)

Lab exercise: Simple calculator and more with data types

Goal

  • To use flow of control, data types and terminal input/output for simple tasks

Methods

  • Set up some variables, then create a main loop that solicits input and provides output. Consider the simplest possible ways of doing things, not the most flexible.
  • Skeleton code:
    #!/usr/bin/perl -w
    use strict;
    my ($a, $b, $oper);
    
    print "Enter the first number: ";
    
    while (<>) {
      $a=$_; chomp($a);
      print "Enter the second number: ";
      $b=<>; chomp($b);
      print "Enter 1 to add, 2 to subtract: ";
      $oper=<>; chomp($oper);
      if ($oper == "1") {
        print "The sum is: " . ($a + $b) . "\n";
      } else {
        print "The difference is: " . ($a - $b) . "\n";
      }
    
    print "Enter the first number: ";
    }
    
  • What is missing in the code above? How would you add error checking? Comment the code, and build upon it.

First ... Back ... Next ... Last ... (Notes home)

UAF Computer Science
Prof. Greg Newby