duperouzel.com

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

Chapter 2 - Program Structure

Contents:

  1. Decisions & Repetitions
  2. If - Then - Else
  3. The 'for' Loop
  4. Chapter 2 Exercises

Decisions & Repetitions


Linear Code

Up until now, our code has simply been a list of instructions to be followed in sequence, one after the other. This is known as Linear or Sequential code:

begin
  <Statement 1  >;
  <Statement 2  >;
  <             >;
  <Statement n-1>;
  <Statement n  >
end.

This sort of code is for programs which do things step by step (and good program design). More complex problems require more sophisticated constructs. These constructs (think of constructs as structured methods), fall into two categories: Conditional (Branching, Decisions) and Repetition (Looping, Iteration).


If - Then - Else


Simple 'if' Statement

Branching code allows different sets of instructions to be programmed for different conditions, hence Conditional constructs. The first of these to get to grips with is the if statement. The syntax is as follows:

          ..>;
  <Statement>;
  if <Condition> then
    <Statement>;
  <Statement>;
  <..
    

The line of code after then is only executed if the condition is true. If the condition is not true, then it is ignored. E.g.:

  if Age < 18 then
    Minor := true;
    

Note in the syntax that there is no semicolon after then, it is all one line of code. If you do put a semicolon after then, the if construct is ended and following line is executed unconditionally.

More Complex 'if'

You can put multiple instructions within an if statement if necessary. As with all blocks of Pascal code, they must be between a begin and end though as follows:

          ..>;
  <Statement>;
  if <Condition> then
    begin
      <Statement>;
      <..        ;
              ..>;
      <Statement>
    end;
  <Statement>;
  <..

  <Statement>;
  if Age < 18 then
    begin
      Minor := True;
      WriteLn( 'You're not allowed to vote yet' )
    end;
  <Statement>
    

Take a careful note of where all the semicolons go! Pascal can be very unforgiving (quite rightly so!) on this, it is a common pitfall for the inexperienced. The indentation is also important. It allows the code to be examined easily for errors. The way the blocks of code are laid out should reflect the precise design of the solution.

The 'else' Part

The simple if statement does nothing if the condition is not true. The else part of the statement allows us to add alternative code to be executed where necessary. The syntax in it's simplest form is as follows:

          ..>;
  <Statement>;
  if <Condition> then
    <Statement A>
  else
    <Statement B>;
  <Statement>;
  <..
    

If the condition is true, then statement A is executed and statement B ignored. If the condition equates to false however, Statement A is ignored and Statement B is executed. Again, the syntax is very strict. If you were to put a semicolon after either the then, Statement A, or the else, the statement would be ended prematurely and the program would not behave as intended.

  if Age < 18 then
    Minor := true
  else
    Minor := false;
    

Blocks of code (multiple instructions) can also be inserted in just the same way as the if part, bounded by begin and end. Again, care is needed in placing the semicolons, but by now the pattern should start to seem familiar. Take note also of the way the code is indented to accentuate the logical blocks of code. When creating complex 'decision trees', using multiple blocks of code, it becomes very helpful to label each end statement:

          ..>;
  <Statement>;
  if <Condition> then
    begin
      <Statement>;
      <..        ;
              ..>;
      <Statement>
    end { if }
  else
    begin
      <Statement>;
      <..        ;
              ..>;
      <Statement>
    end; { else }
  <Statement>;
  <..

  <Statement>;
  if Age < 18 then
    begin
      Minor := true;
      WriteLn( 'You're not allowed to vote yet' )
    end { if }
  else
    begin
      Minor := false;
      WriteLn( 'You are eligible to vote' )      
    end;
  <Statement>
    

The 'for' Loop


Syntax and usage

The simplest form of repetition is the for loop. The only drawback is that the loop is controlled by a counter. In normal use, we have to know in advance how many times the loop must be executed. The syntax for repeating single and multiple statements is as follows:

{Single statement}
for <counter> := <first> to <last> do
  <statement>;

{Multiple statements}
for <counter> := <first> to <last> do
  begin
    <statement 1>;
    <.           
               .>;
    <statement n>
  end; {for}
    

The counter must be of an ordinal type. By this we mean an integer number or perhaps even characters (for Letter := 'a' to 'z' do is perfectly acceptable!). The simplest way to think of this is to realise that we can't execute part iterations e.g. go 3½ times round the loop!

The counter can be referenced from within the loop (see the example below), but it is generally considered bad practice to reassign (alter) the counter from within the loop as this can cause confusing and unpredictable results.

Example:

<Statement>;
Total := 0;
WriteLn( 'Type three numbers below:' );
for Count := 1 to 3 do
  begin
    Write( 'Number ', Count, ': ' );
    ReadLn( Number );
    Total := Total + Number
  end; {for}
WriteLn( 'Their total is: ', Total );
<Statement>;
    

Chapter 2 Exercises


Retirement Age

Design and code a program which prompts for a persons age and gender and decides whether the person is above official retirement age. Use ages 65 for men and 60 for women. Test your program.

Solution


Number Sort

Devise an algorithm and data structure to sort three numbers into ascending order. Design and code a program to prompt for three numbers, sort them into order and display the result to the user.

Solution


Times Table

Write a program which will display the 'times table' (1 to 12) for a user defined number and display it neatly to screen.

Solution


Fixed Compound Interest

The formula for calculating annual interest is I = C * (1 + R/100) per year, where I is the amount of interest, C is the Capital (amount) invested and R is the Rate of interest as a %.

Design a program which will accept a Rate of Interest, original Capital and duration of loan (in whole years) in order to calculate the final value of the investment. The output (e.g. £100 for 3 years @ 5%) should be in the following format:

Fixed Compound Interest:

Capital = £  100.00
Rate    =      5.00%
Term    =  3 years

Capital = £  100.00
Year 1  = £  105.00
Year 2  = £  110.25
Year 3  = £  115.76
    

Solution


Times Tables

Write a program which writes all the times tables (1 times, 2 times, etc.., up to the 10 time table) using nested For loops. The program should stop after each table and await a response from the user to continue, otherwise the output will scroll off the screen

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