Unit 1 · Basics of Computer Programming

1.1.4Self-check and practice

Self-check questions

Write your answers first, then open the answers to check them.

  1. List four properties of an algorithm.
  2. Why must an algorithm be finite? Give an example of a step list that is not finite.
  3. Which control structure is used when a program must repeat steps?
Show answers
  1. Any four of:

    • Input: zero or more values are supplied.
    • Output: at least one result is produced.
    • Definiteness: every step is clear and unambiguous.
    • Finiteness: it ends after a limited number of steps.
    • Effectiveness: every step is simple enough to carry out.
    • Correctness: it gives the right answer for every valid input.
  2. An algorithm must produce a result, and steps that never end never produce one. Example of a step list that is not finite:

    1. Set x to 1.
    2. Add 1 to x.
    3. Go back to step 2.

    There is no stopping condition, so it runs for ever.

  3. Iteration (a loop), for example WHILE or FOR.

Practice exercises

  1. Write an algorithm to convert a temperature from Celsius to Fahrenheit (F = C × 9/5 + 32).
    Hint

    READ c then f = c * 9 / 5 + 32 then PRINT f.

  2. Write an algorithm to decide whether a number is even or odd.
    Hint

    Use the remainder: if n MOD 2 = 0 the number is even, otherwise it is odd.

  3. Write an algorithm to find the sum of all even numbers from 1 to 100.
    Hint
    Pseudocode
    total = 0
    FOR i = 2 TO 100 STEP 2 DO
      total = total + i
    END FOR
    PRINT total

    The answer is 2550.

  4. Write an algorithm for withdrawing cash from an ATM, including the case of insufficient balance.
    Hint

    Read the PIN and the amount. Use a selection: if the amount is greater than the balance, display "Insufficient balance"; otherwise subtract it and dispense the cash.