Tutorial: Simple Program Structure

Last updated 26 June 2006

This tutorial introduces a few basic executable statements and the minimum program structure to use them in simple programs.  These programs are limited to only generating output by themselves.  They take no input from the user or other sources. 

For the purpose of this tutorial, programs are structured as follows:

program program-name;

var
  variable definitions

begin
  executable statements
  end.

The variable definitions section is only necessary if variables are used, but any program that does more than just write a fixed message will require variables. 

Comments

An important part of any program is comments.  These were not shown in the basic structure above because they can be inserted just about anywhere, and are not strictly required by the compiler. 

A comment is something the compiler specifically ignores.  This means comments are for you and anyone else reading the program.  Because you might want to use arbitrary english text to describe why you did something the way you did it, comments are a way of telling the compiler to ignore some text.  Pascal comments start with the left curly bracket character "{" and end with the right curly bracket character "}".  The curly brackets and everything in between are ignored by the compiler.  You can put a comment anywhere it would be legal to put a space.  Comments can span multiple lines.  Once the compiler sees a "{", it just keeps ignoring text, for as many lines as it takes, until is finds a "}". 

We will use comments two different ways.  The first is a block of lines that is all one comment.  This is called a "block comment".  For now you start these with a line containing just "{", then write your note on subsequent lines starting with "*   ", then end the comment with a line containing just "}".  If the block comment is at the beginning of the file, you can write your note starting on the same line as the "{".  Block comments are used to describe the following section of code, or everything in a file for the comment at the start of the file. 

The other type of comment is after everything else on the same line.  These are called "end of line" comments.  You write the "{", then a few words, then the "}" all on the same line.  End of line comments are used to explain the purpose of just the line they are on.  There is very little space at the end of a line to explain what that line is doing, so you should spend it to explain the purpose of the line, not the raw mechanics that anyone familiar with Pascal already knows.  For example:

  count := count + 1;  {add 1 to count}

is a useless comment since anyone familiar with Pascal already can see that this statement adds 1 to count (as you soon will too).  A much more helpful comment is:

  count := count + 1;  {count one more person in the building}

Note how that tells you the purpose of the statement, not just the mechanics of what the statement is doing, which we already know. 

Here is an example of different comments in part of a program:

{   Program TANKLEV
*
*   This program monitors the level in the tank and tries to maintain
*   it within normal operating limits.  If the level gets too low, it
*   turns on the feed pump.  If the level gets too high, it opens the
*   drain valve and the excess flows out behind the garage into the
*   brook.  It is recommended to not run this program when an EPA
*   inspector is on the premises. 
}
program tanklev;

var
  gallons: integer;           {gallons of sludge currently in the tank}

Symbols

Various entities will be referred to as being "symbols".  A symbol is just the name of something, identified so that the compiler can recognize it as a name and not just ordinary text.  A string of characters is recognized as a symbol by where it is relative to kewords and other program elements, and by the characters it contains.  For now, symbols can contain only the ordinary letters A-Z, the underscore character (_), and the digits 0-9.  However the digits 0-9, if used, must not be the first character of a symbol.  In other words, symbols can't start with a digit.  Symbols are mostly case-insensitive, but there are exceptions not worth getting into at this point.  For now, just use lower case.  This is what all the examples do, and it is easier to type since you don't have to keep hitting the SHIFT and CAPS LOCK keys. 

For example, these are legal symbols:

counter
tank_level
lot1
lot2

But these are not legal symbols:

1lot
2lot
tank level

The first two are illegal because they start with a digit.  The last is illegal since it contains a space. 

Variables

Variables are containers for values, like numbers and text strings.  In executable code, you can stick things in variables, then recall them later. 

Before you can use a variable, you have to define it so that the compiler can reserve memory for it and understand later what you mean when you use the variable.  This is the purpose of the variable definition section that starts with the var keyword.  Each variable definition in this section has the form:

  variable-name: data-type;

The variable-name part is a symbol (see previous section).  This tells the compiler that from now on when you use that symbol, you are referring to the variable. 

The data-type part defines what type of information the variable will hold.  Data types can get complex, but for now we are going to stick to one simple data type:

  integer

A variable defined to have this data type can take on an integer value.  For example, it can be assigned the value 2, 27 or -3, but not 3.14.  This particular type of integer (there are other integer types we'll get into later) has a limit in that it can only hold values from -32768 to 32767, but that shouldn't get in our way when writing our first few programs. 

Here is an example of a complete variable definitions section.  This would go after the program statement and before the begin at the start of the executable section:

var
  people_in: integer;    {number of people in the building}
  people_out: integer;   {number of people outside trying to break in}
  dogs: integer;         {number of dogs currently patrolling the perimeter}

Expressions

An expression is something that specifies a value, such as you might print out, assign to a variable, or compare to another value.  The simplest expressions are just constants such as "2", "127", or "-39".  The name of a variable represents the value last assigned to that variable.  From the example of the previous section, "people_in" and "dogs" are also simple expressions when used in executable code. 

So far these expressions contained only a single term, which was a constant or a variable name.  You can make more complicated expressions by combining multiple terms with operators.  There are many operators in Pascal, but for now we'll stick to just four:

+

Addition.  The terms on either side are added together to form the expression value.  For example, 27 + 5 has the value 32. 

-

Subtraction.  The term on the right side is subtracted from the term on the left side to make the expression value.  For example, 27 - 5 has the value 22. 

*

Multiplication.  The terms on either side are multiplied together to form the expression value.  For example, 27 * 5 has the value 135. 

div

Integer division.  The term on the left side is divided by the term on the right side to make the expression value.  However, there is a wrinkle.  This particular divide operator (there are others we'll get into later) always produces an integer result.  Any fractional part that would normally result is discarded.  This is just like doing a divide with a remainder, but tossing out the remainder when done.  For example, 27 divided by 5 is 5.4 or 5 remainder 2, but in Pascal 27 div 5 has the value 5. 

More than one operator can be used in an expression.  For example, 27 + 3 - 5 is a legal expression with the value 25. 

Note that expressions can get ambiguous when order-dependent operators like - and div are used.  For example, what is the value of 27 - 3 + 5?  Clearly we start with 27, but do we then subtract 3 and then add 5, or subtract the value of 3 + 5?  The first would have a value of 29, and the second a value of 19, so this matters.  And what about 27 -  3 * 2 + 5? 

Each type of operator has a "precendence level" in the compiler.  The operations of operators with high precedence are performed first.  Operations of the same precedence are performed in left to right order within the expression.  For the four operators that have been introduced so far, * and div have the same high precedence, and + and - the same lower precedence. 

So let's examine the example expression 27 -  3 * 2 + 5.  The * operator has higher precedence than the others, so its operation is performed first.  That means 3 * 2 is resolved to 6, and the expression is now 27 - 6 + 5.  The - and + operators have the same precedence, so they are performed in left to righ order.  This means 27 - 6 is performed first, leaving 21 + 5, which resolves to 26.  So the value of "27 - 3 * 2 + 5" is 26. 

Even though there are clear rules for how to interpret such expressions, it is not a good idea to write code that would needlessly confuse people that might look at it.  At best even someone who knows the rules still has to stop and "figure out" what the expression means. 

Wouldn't it be nice to have a clear way to specify the operator precedence?  And what if you really wanted to perform 27 + 5 first, then divide the result by 3?  If you wrote 27 + 5 div 3 Pascal would first divide 5 by 3, then add 27. 

The answer, just like in real math, is parenthesis.  Anything inside parenthesis is evaluated as a separate expression regardless of what is outside the parenthesis.  For example, (27 + 5) div 3 specifies that 27 and 5 are added together as a separate operation, then the whole result divided by 3.  The result is 32 div 3, which is 10 (remember, the remainder gets tossed).  Paranthesis can also be nested (parenthesis within parenthesis), just like in real math with the same effect. 

Executable Statements

Executable statements perform the "work" of the program.  The term "executable" means that these statements "execute" or perform operations, as apposed to other statements that define things, like the name of the program or the name and type of a variable. 

There are a number of executable statement types in Pascal, but for now we're going to stick to just a few:

Assignment

An assigment statement assigns a value to a variable.  After an assignment statement the variable retains the value until another value is assigned to it.  An assignment statement has the form:

  variable-name := expression;

For example:

  tank_level := 0;                     {tank starts out empty after cleaning}
  moved_in := 5;                       {let another group of 5 into the building}
  people_in := people_in + moved_in;   {update number in the building}
  people_out := people_out - moved in; {update number outside}

writeln statement

A writeln statement writes output from the program.  For now this is the only means of getting any information out of the program, or getting any confirmation that it is running at all. 

The writeln statement has the form:

  writeln (value, ... value);

For now, value can be an expression or a text string.  Expressions were described above.  A text string is a sequence of characters enclosed in apostrophies ('...').  A writeln statement can have any number of values, including none at all.  The result of all values is concatenated and written to the program's output as a single line.  If the writeln statement has no values, then it writes a blank line to the program's output.  If there are no values, then the parenthesis are also omitted as shown in the example below.

For example, consider the following statements:

  writeln ('Hello, world');
  writeln ('The magic value is ', 42, '.');
  writeln;
  writeln ('Some powers of 2 are:');
  i := 2;                     {initial power of 2}
  writeln ('  ', i);
  i := i * 2;
  writeln ('  ', i);
  i := i * 2;
  writeln ('  ', i);
  i := i * 2;
  writeln ('  ', i);

The program will produce the following output when this section is run:

Hello, world
The magic value is 42. 

Some powers of 2 are:
  2
  4
  8
  16

Compound statement

A compound statement is a way of grouping a sequence of statements so that you can use the group as if it were just a single statement.  This is similar to using parenthesis to turn a complex expression into a single term.  There are cases in Pascal where only a single statement is allowed, but you might want to put multiple statements there.  The solution is to group the multiple statments into a single compound statement. 

A compound statement has the form:

  begin
    multiple statements
    end

In Pascal, from the start of begin to the end of end is a single statement, and you can use it wherever a single statement is allowed.  There will be examples of compound statements used with IF statements below. 

Simple IF statement

A IF statement provides a means to execute another statement, or not, depending on a condition.  The form of a IF statement is:

  if condition then statement;

Condition is two expressions with a comparison operator in between.  The comparison operators used here are <, <=, =, >=, >, and <>.  In order they mean less than, less than or equal to, equal to, greater than or equal to, greater than, and not equal to. 

The IF statement works by executing statement when condition is true, and not if it is false.  For example:

  if 27 > 3 then count := count + 1;    {count will get incremented}
  if 27 < 3 then count := count + 1;    {count stays the same}
  if (level + slop) < 17 then pump := 1; {turn on pump ?}

Often you want to execute a series of statements when the condition is true.  However, only a single statement is allowed after then.  The solution is to use a compound statement.  For example:

  if guards < 2 then begin              {too few guards, some will sneak in ?}
    group := 5;                         {size of group that sneaks in}
    people_out := people_out - group;   {count fewer outside}
    people_in := people_in + group;     {count more inside}
    end;

IF-THEN-ELSE statement

This is like the simple IF statement, except that there are two statements that are conditionally executed.  One is executed if the condition is true, the other if the condition is false. 

This statement has the form:

  if condition
    then true-statement
    else false-statement;

However often a single statement isn't enough for performing the true or false action.  The IF-THEN-ELSE statement is therefore usually used with compound statements like this:

  if condition
    then begin
      true-statements
      end
    else begin
      false-statements
      end
    ;

Note that a compound statement containing only a single statment is perfectly legal, so this form is still preferred even if one or both of the true or false actions are single statements.  As the program is changed, it may be necessary to add additional statements in the true or false sections.  The form with compound statements allows that to be done easily without re-arranging the whole IF statement. 

FOR statement

The real power of computer programs comes from that fact that they can loop over sections of code repeatedly.  You can write the directions for how to do something once, and the computer can perform those actions thousands of times or more.  The FOR statement is a means for doing that.  It can cause a section of code to be executed a particular number of times, and it also provides a unique number, called the index for each iteration. 

The FOR statement has several forms, depending on whether you want the index to go up or down on successive iterations, and whether you want it to go up or down by 1 or some other number.  The forms are:

  for index-variable := start to end do begin
    statements
    end;

  for index-variable := start downto end do begin
    statements
    end;

  for index-variable := start to end by increment do begin
    statements
    end;

  for index-variable := start downto end by decrement do begin
    statements
    end;

Index-variable is the name of a variable that must have been previously defined in the var section, like any variable.  This variable will have a different value for each loop iteration.  You should not try to assign a value to this variable inside the loop. 

For the first iteration, the index variable will have the value of the expression start.  The FOR statement assigns sequential values to the index variable each new iteration of the loop, until the index value goes past the end expression.  The loop will never be run with the index value past end

In the first form of the FOR statement shown above, the index variable is incremented by 1 each iteration.  For example if start is 5 and end is 9, then the loop will be run five times with the index variable being assigned the values 5, 6, 7, 8, and 9 for different iterations, in that order. 

The second form differs from the first in that the downto keyword is used instead of the to keyword.  This causes the index variable to be decremented by 1 instead of incremented by 1 on successive iterations of the loop.  This also means that end must be less than start for the loop to be executed at all.  For example if start is 11 and end is 7, then the loop will be run five times with the index variable having values of 11, 10, 9, 8, and 7 on successive iterations. 

The third and fourth forms are like the first and second forms, except that you get to explicitly set the increment or decrement value instead of it automatically being 1.  Leaving out the "by value" part is just like writing "by 1". 

Here are a few example FOR statements with the number of loop iterations and the index variable shown:

  for page := 1 to 7 do begin
    {will be executed 7 times, with page = 1, 2, 3, 4, 5, 6, and 7}
    end;

  currpage := 5;                       {set current page}
  endpage := currpage * 2;             {set last page to examine}
  for oddpage := currpage to endpage by 2 do begin
    {executed 3 time, oddpage = 5, 7, and 9}
    end;

  lastpage := 33;                      {last page in booklet}
  for page := lastpage downto 1 by 5 do begin {backwards 5 pages at a time}
    {executed 7 times, page = 33, 28, 23, 18, 13, 8, 3}
    end;

  for page := 9 to 3 do begin
    {will not be exceuted at all since the first value would already
     be past the end value}
    end;

First whole program

Below is about as simple a program as possible.  It contains the bare minimum Pascal constructs for a whole program plus the statement to write one fixed message to the output:

{   Program HELLO
*
*   Very simple test program that writes out "Hello, world.", then
*   exits. 
}
program hello;

begin
  writeln ('Hello, world.');
  end

The source file is hello.pas, which you can download and save on your system.  If the Pascal build environment is set up properly, you can run "run_pas hello".  This will translate the Pascal to the intermediate language used on your system, compile that, link it with system and Embed Inc libraries to produce an executable program, run the program, then delete it.  Here is the command shell session that does this on a Windows system. 

C:\www\pascal>run_pas hello
hello.c
Linking executable hello
   Creating library hello.lib and object hello.exp

----------------------------------------

Hello, world. 

Counting example

The previous program was useful in verifying the build environment was properly set up, but it did little real work.  Let's do a simple example that counts and writes the numbers to the output.  Here is program count1.pas:

{   Program COUNT1
*
*   Counts from 1 to 10 and writes the numbers to the output. 
}
program count1;

var
  i: integer;                          {the current number}

begin
  for i := 1 to 10 do begin            {once for each number to count to}
    writeln (i);                       {write the current number}
    end;                               {back for next number}
  end

A session running the program looks like this:

C:\www\pascal>run_pas count1
count1.c
Linking executable count1
   Creating library count1.lib and object count1.exp

----------------------------------------

1
2
3
4
5
6
7
8
9
10

Problems

  1. Modify COUNT1 to count only odd numbers from 3 to 100. 

    Answer: count2.pas

  2. Modify the program from the previous problem to only print those numbers it counts that are prime. 

    Hint 1: Think about how to detect whether a number is prime or not.  How would you write Pascal code to implement that check?  Once you have that code, apply it to the loop index each iteration, and only write the index value if it passes the test. 

    Hint 2: You can use a variable to remember which of two cases was found, then do a IF on that variable later.  For example, you could use p = 1 to mean a number is prime and p = 0 to mean it is not, then later write out the number only if p = 1. 

    Hint 3: You can insert writeln statements at various places to see what the program is doing.  For example "writeln ('J = ', j);" will show the value of the variable j whenever the statement is executed.

    Hint 4: You can debug your program with a smaller range of possible numbers.  For example, the odd numbers from 3 to 10 contain three primes (3, 5, 7) and one non-prime (9).  You can expand the range once the program works correctly on the limited range.

    Answer: prime1.pas.  Many other answers are possible.