duperouzel.com

| Home | Part 1 | Part 2 | Part 3 |

Chapter 1 - Introduction

Contents:

  1. Overview of Programming
  2. Sample Programs
  3. Some Formal Pascal Rules
  4. Formatting Output
  5. Pascal Arithmetic
  6. Chapter 1 Exercises

Overview of programming


Programming Languages

A computer program at its simplest form is a list of instructions. Those instructions are written in a syntax (or programming language) which is as near as possible to natural language (e.g. English). Those instructions (program code) are then 'translated' into machine code (sometimes called hexadecimal because it uses a base 16 numbering system), which is the mathematical 'language' used internally by the computer and may look something like this:

A8 15 26
FF E5 B2 3C
12 FA AC 15
18 AD 06
FF FF
FF 0C
A8 56 FF 00

Apart from programmers who need direct access to the processor (as in microelectronic systems), the hexadecimal language is much too 'alien' to human beings and is too unwieldy to write large programs with any ease or accuracy. A high level language is a definition of a syntax (rules for writing the language code) plus an accompanying compiler which translates the program code to the hexadecimal required by the computer system. The language we are using is a version of Pascal.

 


Sample Programs


Input (keyboard) and Output (monitor)

 
program Hello;

var
  Name : String;

begin
  WriteLn('Enter your name and press <ENTER>.');
  ReadLn( Name);
  WriteLn('Hello ', Name, '.')
end.
    

The first line of the code is the program declaration, It identifies what is to follow, a program named Hello . The second line declares a variable called Name to hold a string of characters.

The actual program code comes between the first begin and the last end, which always has a full stop. The first line of code uses the WriteLn command to output "Enter your name and press <RETURN>." to the monitor. The user prompt. The program then stops. The ReadLn command waits until the user has typed in their name. As soon as they hit the enter key, their name (or whatever else they type) is transferred to the area of program memory identified as Name earlier. The final line uses the WriteLn command again, but this time writes a list of three things to the monitor: "Hello " with the space after it, then whatever is represented by Name - exactly what was typed in by the user, then a full stop to finish it off.

Input, Calculation and Output

The last program simply 'remembered' some typed characters and then typed them back to the user. The following code does something more in between:

program InchToCent;

const
  CentPerInch = 2.54;

var
  Inch,
  Cent : Real;

begin
  WriteLn('Enter the length in inches> ');
  ReadLn( Inch );
  Cent := CentPerInch * Inch;
  WriteLn('That equals ', Cent, ' centimetres.')
end.

The program definition in this instance has the same program and var (variable) definition lines as the previous one. It is a program, called InchToCent. There is an extra line next with the word const. This part of the declaration is for data necessary to execute the program successfully. This sort of data does not alter while the program is running, so it declared as 'constant'. In this case it is the conversion factor, the number of Centimetres to the Inch.

There are two variable declarations in this program: Inch and Cent, which are declared as Real. The last program allocated memory for a string of characters. This one allocates space for two real numbers. Real numbers store a 'floating point' value which means a number with a decimal place.

The first line of code executes a "user prompt" like the first program, this time to prompt for a length in inches. Again, there is also a line to read in the response at the enter key - this time to store a number in the variable Inch. In this program, the third line does a calculation. The number typed in by the user, Inch is multiplied by the number represented by InchToCent (2.54) and the result assigned to Cent. The centigrade equivalent (Cent) is displayed to the user in the final line.

 


Some Formal Pascal Rules


Pascal Code

Pascal code is nice in that we can read it, at least in a way! It is a 'high level' language, which means that the code resembles natural English as much as possible. The snag is that the code still has to be written in a very rigid and disciplined way. Natural language is far too vague to construct a set of instructions which are eventually going to be executed by something as precise as a processor.

This discipline is called syntax - it is what defines Pascal as opposed to other languages. It is good practice to write code in a neat, structured and consistent way. The structure of the document should always reflect the structure of the code.

The programs here have had two parts. The declaration part (program, const & var) and the code (between begin & end.). These two parts equate to the parts of a recipe. The first part of a recipe is usually the ingredients list, with perhaps a list of equipment and cooking / preparation time - the requirements! This is the same with the declaration. Here you list all the requirements of the program.

The code equates to the instructions or directions of the recipe, the second part - the order of preparation - what to do, step by step.

Common Syntax Rules

Pascal syntax is quite intuitive because it is very consistent and logical. As you begin to understand some of the rules, you find you can guess at the rules for unfamiliar constructs very quickly. Statements (lines of declaration or lines of code) are separated by the semicolon ';'. List items are separated by commas ','. Discrete (or logical) blocks of code are separated by begin and end words. A range of values is separated by a double dot ellipsis '..'.

var                              { Declaration clause...        }
  First,                         { of five Real numbers         }
  Second,                        { separated by commas          }
  Third,                         { and separated from the next  }
  Sum,                           { declaration statement by the }
  Average : Real;                { semicolon.                   }
  List : array[ 1..10 ] of Real; { Range of 1 to 10 in square   }
                                       { brackets }

begin
  <Statement 1>;     { A logical block of pascal statements... }
  <Statement 2>;     { Separated by semicolons and             }
  <           >;     { delimited by the begin and end          }
  <Statement n-1>;   { reserved words.                         }
  <Statement n>
end;
    

Blocks of code can be nested i.e. one block inside another:

begin
  <Statement>;
  <Statement>;
  begin
    <Statement>;
    <Statement>;
    <...
           ...>;
    <Statement>;
    <Statement>
  end;
  <Statement>;
  <Statement>
end;
    

Reserved Words & Identifiers

Reserved words are those which Pascal uses as part of its language syntax. You can not redefine them (e.g. use them as variable names). These are the words which show up in white in the Turbo Pascal 7 editor. The reserved words in the two sample programs so far are:

program, var, string, begin, end, const.

Identifiers are things like variable, program and constant names. These fall into two categories. The first category is those identifiers defined by Borland for use in the Turbo Pascal language. The ReadLn and WriteLn functions are an example of these. These functions are defined, identified and provided by Borland Pascal. Unlike reserved words, you can redefine these and use them for something else, but to do so would not usually be beneficial.

The Borland Pascal identifiers in the previous programs are the ReadLn, WriteLn and Real statements. The other identifiers are:

Hello, Name, InchToCent, CentPerInch, Inch, Cent

Some Data Types

When variables are declared, they are given 'types' e.g.:

var
  Name   : String;
  Number : Real;
    

The 'type' determines what sort of data is to be stored and how much memory is allocated to it. The common data types in Pascal are listed below:

Type

Example

 

Memory
Required

Char

"z"

A single ASCII character

1 Byte

String

"Fred Bloggs"

A string of characters (text). The default length is 255, but can also be defined.

1-255 Bytes

Integer

2593

A whole number - no decimal point or fractions. -32768 to 32767.

2 Bytes

Real

45.892

A floating point number, accurate to 10 or 11 decimal places.

6 Bytes

Boolean

"True" or "False"

Often used as flags or to store the result of relational operations.

1 Byte

There are many other 'types', most of them are variations of the ones above. Some give greater accuracy to the number types, some provide greater flexibility to the programmer. As you progress through the course, you will also learn how to define your own data types.

 


Formatting Output


Text

A string can be formatted to appear right - justified within a defined field width. If the field width is longer than the string, spaces are inserted to the left of the string. E.g.:

WriteLn( 'Vauxhall' :10 );
WriteLn( 'Ford' :10 );
WriteLn( 'Peugeot' :10 );
WriteLn( 'BMW' :10 )
    

Would appear on the output as:

  Vauxhall
      Ford
   Peugeot
       BMW
    

Integers

The same field width can be applied to integers:

WriteLn( 'Vauxhall' :10, 485 :4 );
WriteLn( 'Ford' :10, 26 :4 );
WriteLn( 'Peugeot' :10, 205 :4 );
WriteLn( 'BMW' :10, 525 :4 )
    

Would appear on the output as:

  Vauxhall 485
      Ford  26
   Peugeot 205
       BMW 525
    

Real

The real numbers have an extra parameter to specify the number of decimal places after the fieldwidth parameter:

WriteLn( 'Vauxhall' :10, 48.5 :6 :2 );
WriteLn( 'Ford' :10, 26 :6 :2 );
WriteLn( 'Peugeot' :10, -2.05 :6 :2 );
WriteLn( 'BMW' :10, 52.5 :6 :2 )
    

Would appear on the output as:

  Vauxhall 48.50
      Ford 26.00
   Peugeot -2.05
       BMW 52.50
    

All the above examples use literal strings and numbers. This is for illustration only. Exactly the same effects can be used using string or number variables instead e.g.: WriteLn( RevsPerMin :10 :2 ) is valid provided RevsPerMin is declared as a Real number. In fact, variables can also be used to represent the field width and decimal place values!

 


Pascal Arithmetic


Pascal does arithmetic in a broadly similar manner to the notation we're used to. There are only two pitfalls:

  1. Getting the order of the equation correct. 6 * 3 + 2 / 4 = 5 if evaluated from left to right. From right to left it comes to 21. Pascal would evaluate it as 18.5! (This is always a consideration within mathematics, not peculiar to pascal.)
  2. Careful thought must be given to variable types when calculation is involved. Real and Integer variables can only be mixed in certain combinations. An Integer can never be the result of an ordinary division for example!

Operator Precedence

  1. Expressions within brackets (parentheses) are evaluated first. If there are brackets within brackets (nested parentheses), then the innermost brackets are evaluated first and so on outwards.
  2. Multiplication and division operations are evaluated. *, /, mod and div (mod and div are integer operations as below).
  3. Addition and subtraction operations.

The example 6 * 3 + 2 / 4 would be evaluated as:

  • Rule 1 - No parentheses, no change. 6 * 3 + 2 / 4
  • Rule 2 - Evaluate multiplication and division: 18 + 0.5
  • Rule 3 - Perform the addition: 18.5

Integer and Real Arithmetic

We use different variable types to represent these two types of numbers because Pascal handles them in very different ways. Because of this, we must be careful when using numbers in arithmetic operations. We must be certain that the variable which takes the result of an arithmetic operation is of the correct type. The rule of thumb is that if there is a Real number in the operation then the result must be Real. This holds true except for division, where the result of a division must always be of type Real.

Integer Division

There are special operators to do division arithmetic with Integer numbers. Instead of the "/" character, we use the div and mod operators. These allow us to perform division and still use integer numbers. Here, instead of working out the answer to a certain decimal place, the division is performed and a remainder given where appropriate. The div operator returns the result of the division. The mod operator returns the remainder. E.g.:

begin
  A := 50;
  B :=  7;
  X := A div B;   { X = 7 (7*7=49) }
  Y := A mod B;	{ Y = 1 (50/7 = 7 rem 1) }
end.
    

Chapter 1 Exercises


Type in the following programs. Compile and run them:

program Hello;

var
  Name : String;

begin
  WriteLn('Enter your name and press <RETURN>.');
  ReadLn( Name);
  WriteLn('Hello ', Name, '.')
end.
    

When you have typed in the program, save it to disc with the name hello.pas. To open a new file for the next program click on File|New.

program InchToCent;

const
  CentPerInch = 2.54;

var
  Inch,
  Cent : Real;

begin
  WriteLn('Enter the length in inches> ');
  ReadLn( Inch );
  Cent := CentPerInch * Inch;
  WriteLn('That equals ', Cent, ' centimetres.')
end.

Modify the last program to convert from centimetres to inches.

Before you start this task, first save the previous code as intocen.pas. Then, look at the code and decide which parts you need to alter in order to convert the program. Before you start to type your alterations, you must save the file under a new name, using File|saveAs as centoin.pas. By doing this, you create a separate document for your modifications.
(The conversion factor is 0.39 inches per centimetre)

Solution


Write a program to read three numbers from the user.

Using the skills you have gained (and borrowing code from the above) write a program which prompts for three numbers from the user. The program must display the three numbers along with their sum and average.

Solution


Invoice Problem

Write a program which prompts first for a company name then for the details of three products: Product, Price and Quantity. The program should calculate the total price for each product (price * quantity) and the total for the invoice before and after VAT at 17.5%. The output should be of the following format:

INVOICE
<Company Name>

             Grommet   15 @ £   0.12 £    1.80
              Widget   19 @ £   4.00 £   76.00
           Thingummy   10 @ £   0.01 £    0.10
                                      --------
                               Total £   77.90
                         VAT @ 17.5% £   13.63
                                      --------
                       Invoice Total £   91.53

Solution


Wages Breakdown

Design an algorithm which will break down a wage into the different denominations required to make up the exact amount to be paid. Format the output into a neat table, where all the decimal points line up, which shows how many notes/coins and the amount for each denomination along with the total at the bottom.

Hint: This code is not as trivial as the previous questions. It will certainly require planning to perform the Integer & Real arithmetic correctly. You may find you can improve the code by researching the rounding functions provided by Pascal. There are details and examples of the functions in the Help files provided with the Pascal editor.

Solution


© 1997-2001 Dave Duperouzel.

You are free to print these pages for teaching and learning purposes, provided they are printed in entirety and all acknowledgements to the author are left intact.

Design & Implementation by Dave Duperouzel @ duperouzel.com

duperouzel.com