DAT2322 - Course Notes

Introduction to Computer Programming

Prepared by Maitang Mark
March, 2000

Lesson 1

The Fundamentals of Computer Programming

    In this lesson, you will
  • learn to define a computer program.
  • learn to write simple Perl programs.
  • learn about the Perl instructions - PRINT and ASSIGNMENT.
  • learn about variables and constants.
  • learn about string and numeric data values.

What is a computer program?

  A computer program is a set of instructions for the computer to execute in order to complete certain tasks. In our daily life, we deal with instructions all the time. For example, to get to Parliament Hill from the Woodroffe campus of Algonquin College, the instructions would be:
    The Table of Contents
 
  1. From the main entrance turn right onto Woodroffe Avenue.
  2. After three sets of traffic lights, turn right onto the Queensway East.
  3. When you reach the Nicholas Street exit, exit the Queensway onto Nicholas Street.
  4. After three sets of traffic lights, turn left onto Rideau Street.
  5. After three blocks, you will see Parliament Hill on the right.

 
  Most likely you will have a little difficulty in driving there using these instructions. Natural languages such as English are adequate when you want to talk with another person. There is a "background of obviousness", a shared common experience that forms the basis for human communication. This does not exist for human-computer communication. Natural languages are far too imprecise when you want to instruct a machine. For that, you need to use a programming language such as Perl. The instructions in a programming language will cause the computer to interpret them the same way every time.  
| To top |

Creating your first Perl program

  For step-by-step illustration of how to create the following Perl program, click Instructions here.
 

Program 1.1. The hello.pl program.


# hello.pl	This program prints a hello message.
#
    print "Hello World !";
  The first two lines are comment lines and they are not executed. This means that the computer will ignore these lines of text. They are there for the benefit of programmers. The purpose of comments is to add documentation to a program.

The first line reminds the programmer what the program is about. The second line is a blank comment line which separates the header comment and the code body of the program. It just spreads out the lines so that they are easier for you, the programmer, to read.

  Comments
    are not
    executable.
  This program has only one line to be executed. That is the print instruction. The print command must be followed by what is to be printed. In this case, it is the phrase "Hello World!". The semicolon terminates the instruction.

Save the program on the diskette in A: drive and call it hello.pl where the file extension .pl implies that it is a Perl program.

  Semicolons
    terminate
    instructions.
 
  | To top |

Creating your second Perl program

  Apply the same steps you learned on the last program and compose the following Perl program.

Program 1.2. The weekday.pl program.


# weekday.pl	This program prints a sentence using a variable
#
    $weekday = "Friday"; 
    print "I wish today was ", $weekday;
The result of the above program displays the sentence on one line:
 I wish today was Friday 
  The above program displays a string literal " I wish today was " followed by a comma (,). The comma means there is more to print. It is followed by the variable $weekday. What is being printed is the value of the variable, not the variable name. The last semicolon (;) terminates the print instruction.

If you would like to see a period printed after the sentence, you must change the print instruction to:

      print " I wish today was ", $weekday, ".";

Put a comma (,) after the variable $weekday and add another string literal "." before terminating the instruction.

  The print statement prints
    the value of the variable
    instead of the name of
    the variable.
  You may mix as many literals and variables as you like in one print instruction provided that you separate them with commas (,) and terminate the instruction with a semicolon (;).
  One print command can
    print many items
    provided that they are
    separated by commas.
  | To top |

The PRINT command

  We speak and write instructions to each other in sentences. In Perl, we use instructions that are very much like sentences, for example:
  print  "Hello World! "; 

The above statement is a print instruction. It displays on the display screen as follows:

  Hello World! 

The print command displays the rest of the statement on the display screen, namely, what is enclosed in the pair of quotes. Note that the quotation marks enclosing the phrase are not displayed. The semicolon following the last quote is not displayed either. The semicolon is used to end the instruction.

    Place words to be
      printed in a pair
      of quotes.
 

The quotation marks and the semi-colon are examples of proper syntax that must be used as part of the instructions for the computer.

    Syntax is the grammar
      of the programming
      language.
| To top |

Constants and variables

 

In Perl, a string of characters enclosed in a pair of quotation marks is called a string constant. The word string is a short name for a string of characters. String constants keep their contents unchanged throughout the running of the entire program.

    Constants do not change.
 

We often give names to things whose value can change. Examples here are time, date, current month, and so on. These are called variables. A variable has a name and a value. As a programmer you will decide what name to give to a variable and what value to assign to it. You should select the variable name that describes the type of values it is going to have. If the value is about a distance in miles, call the variable $distance or $miles. If it is going to store quantity of goods sold, call the variable $quantity or $goodsSold, etc. All single value variable names start with the dollar sign ($).

    A variable changes its
      value in a program.

The Assignment command

  Perl uses the assignment command to assign a value to a variable:
  $weekday = "Friday"; 
 

The assignment command appears as an equal sign (=). The left side of the equal sign must be a variable. The right side of the equal sign can be either a constant or a variable. The above assignment statement causes the variable $weekday to be given the value "Friday".

The following assignment instruction:

  $holiday = $weekday; 
    The = sign assigns
      from right to left.
 

assigns the value of the variable $weekday to the variable $holiday. The variable on the left side of the equal sign has its former value replaced with the value of whatever is on the right side. There can only be one variable on the left side of the equal sign. The value at the right side of the equal sign is not changed. It is possible to have either a constant or a variable at the right side of the equal sign since its value remains unchanged. A variable retains its assigned value for the life of the program, or until it is assigned a new value. Now both variables $weekday and $holiday are string variables as they both contain a string value.

For the above example, the variable $weekday has the value "Friday". Therefore, the variable: $holiday is now assigned the value "Friday".

Another type of value is the numeric value. The following assignment:

  $miles = 50; 
    The left side of an
      = sign must be a
      variable.
 

assigns the variable $miles a numeric value of 50. The 50 is a numeric constant. A numeric constant does not require to be enclosed in a pair of quotes like the string constant. The variable $miles is called a numeric variable because it contains a numeric value.

   $speedLimit = $miles; 

The above assignment assigns the value of the variable $miles, which is 50, to the variable $speedLimit.

    Do not enclose
    numeric constants
    in a pair of quotes.
 

A variable name must start with the dollar sign and be followed by an alphabetic letter. The rest of the name can be alphabetic (a-z), digits (0-9), or underscore (_). It can be as long as you want. Variable names are case sensitive. Miles, miles, and MILES are three different variables.

    Variable names are
      case sensitive and
      contain only letters,
      digits, and underscore.
| To top |

Displaying more than one line using one print instruction

 

Program 1.3. Use the text editor to compose the following program:


# speed.pl	This program prints multiple lines
#
    $mySpeed=100;
    $speedLimit = 80;
    print   " I am driving ", $mySpeed, " kilometers per hour. \n", "The ",
  	    " speed limit here is ", $speedLimit, " kilometers per hour.";
The result of the above program displays the sentence in two lines:

  I am driving 100 kilometers per hour.
  The speed limit here is 80 kilometers per hour. 
 

The symbol backslash followed by a letter n (\n) represents the newline character. It serves the same function as the hard return code in WordPerfect. It causes the print instruction to start a new line of output on the display screen. Try to delete \n and run the program again. These two sentences will then be displayed on the same line.

Program 1.3 also demonstrates that a print instruction can span more than one line, as long as the items to be displayed are separated by commas (,).

The print instruction can be rewritten in the following fashion and still produces the same result as that from Program 1.3


print   " I am driving ", 
        $mySpeed, 
        " kilometers per hour. \n", 
        " The ",
        "speed limit here is ", 
        $speedLimit, 
        " kilometers per hour. ";
\n is a new line symbol.
\t is a tab symbol.
 

Note also, all of the string literals contain a blank space on both ends. Take the blank off before the last kilometers, run the program, and check out the results. They become hard to read. It is a good practice always to put a blank between two items in a print instruction. The result is a better presented sentence.

    Spaces can improve
    output presentation.
| To top |

Variables can save typing

 

Program 1.4. Use the text editor to compose the following program:


# song.pl	The morning song program
#
    $verse1="This is the way we ";
    $verse2=" wash our face, \n";
    $verse3=" so early in the morning. \n";
    print   $verse1, $verse2, $verse2, $verse2, $verse1, $verse2, $verse3;
The result of above program after execution is:

This is the way we wash our face, 
 wash our face, 
 wash our face,
This is the way we wash our face, 
 so early in the morning. 
 

The advantages of using variables is that once you have a variable with a certain value, such as " wash our face, ", it can be used again and again in the program. In a small program, this advantage is less obvious. In a large program, variables can save programmers a lot of time and typing mistakes. The punctuation in the above example is not perfect. However, it serves to demonstrate how to reuse a variable. As a part of the exercises, try to find a way to improve the punctuation.

    Variables save times
      and mistakes.
| To top |

Lession 1 Exercises

  1. Name a variable that can be used to store the weight of a truck.

  2. Name a variable that can be used to store the distance to travel by a truck.

  3. Name a variable that can be used to store the cost of shipping goods by truck.

  4. Given a variable $dozen, write a statement to assign it a value of 12. Write a statement using $dozen to display "12 make a dozen."

  5. Given a variable $ozPerPound, write a statement to assign it a value of 16. Write a statement using $ozPerPound to display "A pound has 16 ounces."

  6. Given a variable $inPerFoot, write a statement to assign it a value of 12. Write a statement using $inPerFootdozen to display "A foot has 12 inches."

  7. Given a variable $passingGrade, write a statement to assign it a value of 50. Write a statement using $passingGrade to display "The passing grade for this course is 50."

  8. Given a variable $product, write a statement to assign it a product name (e.g., "StepMaster", "You only live twice", etc.) Display a description of that product. Be sure to use the variable each time you need to include it in your description.

  9. Add two more verses to the sample program 1.4 song.pl above. Use the variables there and add more variables if needed. Display the new song.
| To top |
M. Mark, 2002.03.18 | Introduction | Lesson 1 | Lesson 2 | Lesson 3 | Lesson 4 | Appendix |