We use counting when we need to know how many elements we have.
Examples
An algorithm allows a user to enter numbers until the user enters 0. The algorithm then outputs the amount of numbers that have been entered.
Pseudocode
count ← 0
REPEAT
INPUT number
count ← count + 1
UNTIL number = 0
OUTPUT "The amount of numbers that have been entered are ", count
Count the amount of numbers in the array MyNumbers that are smaller than fifteen.
MyNumbers ← [4, 20, 3, 47, 10, 1]
count ← 0
FOR index ← 0 TO 5
IF MyNumbers[index] < 15
THEN
count ← count + 1
ENDIF
NEXT index
OUTPUT "There are ", count, " numbers in the array MyNumbers that are smaller than fifteen."
We use totalling when we need to add numbers.
Example
Having the array MyNumbers find the total of all its elements.
MyNumbers ← [4, 20, 3, 47, 10, 1]
total ← 0
FOR index ← 0 TO 5
total ← total + MyNumbers[index]
NEXT index
OUTPUT "The total sum of all elements in the array MyNumbers is: ", total
A shop sells books, maps and magazines. Each item is identified by a unique 4 – digit code. All books have a code starting with 1, all maps have a code starting with 2 and all magazines have a code starting with 3. The code 9999 is used to end the algorithm. Write an algorithm in the form of a flowchart which inputs the codes for all items in stock and outputs the number of books, number of maps and the number of magazines in stock. Include any validation checks needed.
Write an algorithm in the form of a flowchart which:
• inputs the top speeds (in km/hr) of 5000 cars
• outputs the fastest speed and the slowest speed
• outputs the average speed of all the 5000 cars