Self-check questions
Write your answers first, then open the answers to check them.
- List four properties of an algorithm.
- Why must an algorithm be finite? Give an example of a step list that is not finite.
- Which control structure is used when a program must repeat steps?
Show answers
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.
An algorithm must produce a result, and steps that never end never produce one. Example of a step list that is not finite:
- Set x to 1.
- Add 1 to x.
- Go back to step 2.
There is no stopping condition, so it runs for ever.
Iteration (a loop), for example
WHILEorFOR.
Practice exercises
- Write an algorithm to convert a temperature from Celsius to Fahrenheit (F = C × 9/5 + 32).
Hint
READ cthenf = c * 9 / 5 + 32thenPRINT f. - Write an algorithm to decide whether a number is even or odd.
Hint
Use the remainder: if
n MOD 2 = 0the number is even, otherwise it is odd. - Write an algorithm to find the sum of all even numbers from 1 to 100.
Hint
Pseudocodetotal = 0 FOR i = 2 TO 100 STEP 2 DO total = total + i END FOR PRINT totalThe answer is 2550.
- 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.