Definition
An algorithm is a well-defined set of step-by-step instructions for solving a problem in a finite amount of time. A set of instructions is not an algorithm if there is no definite stopping place, or if the instructions are too vague to be followed clearly.
Characteristics of a good algorithm
A good algorithm:
- should be explicit (i.e. clear and obvious)
- should be precise (i.e. exact and accurate)
- should be unambiguous (i.e. no doubts about what to do / only one way of interpreting the instructions)
- should be effective (i.e. produce good results)
- should be finite (i.e. have a definite stopping place)
Example: Problem to solve – making pineapple juice
State the step-by-step instructions to follow in order to obtain, at the end, the pineapple juice. Specify the input elements, the result or the output of your algorithm.
- This defines the problem to solve: how to make pineapple juice
- The definite stopping point: when the juice is done
- The above activity is an algorithm to prepare a pineapple juice.
- Pineapple juice is the output
- The ingredients constitute the input
- The cooking steps represent the instruction steps
Exercise: write an algorithm to make a cup of tea
Algorithm Making_a_cup_of_tea
Inputs: Sugar, water, oval tin, milk, fire
Set of instructions:
- Prepare the fire
- Put the pot on the fire
- Boil water
- Put the milk, Ovaltine, sugar inside the tea cup
- Add the boiled water to it
- Stir to make sure that it is uniform
- Test the tea; if it is not OK, perform step 4, else
END Drink your tea
Structure of an Algorithm
To write an algorithm, you have to specify:
- The name of the algorithm which has to be clear and explicit. It should clearly present the problem to be solved.
- The inputs that represent data we need to solve the problem.
- The set of instructions that explains how to solve the problem.
- The output that represents the final result we should obtain.
Example of algorithm: Calculating the surface of a rectangle
Problem: Write an algorithm that calculates the surface of a rectangle.
Algorithm: Surface_of_a_Rectangle;
Inputs: Width: W; Height: H;
Set of instructions:
- Prompt user to enter width and height
- Read the width as W and the height as H
- Compute the surface by multiplying the height H by the width W
- Store the result as S = H × W
END print the surface S
Exercise: Write an algorithm to calculate the surface of a square.
Scenario Creation in Block Programming Environments
- Scratch: a popular block programming environment
- Scenario creation: designing and building interactive stories and games