Implementation (algorithm specification)Count occurrences

Algorithms are created to allow users to tell a computer how to solve a problem. Understanding how to construct five of the most common algorithms is a critical skill for budding software developers.

Part ofComputing ScienceSoftware design and development

Count occurrences

The count occurrences algorithm is used to iterate over an array to count the number of times that a particular value occurs.

The user will usually be asked to enter a value that is to be found within the array. Each time the value is found, one will be added to the total number of occurrences.

Example

In this example, the algorithm is designed to count the number of times that the value 21 is present within an array named ‘age’. In this example it is presumed that the array has already been populated.

Reference language

Line 1 SET occurrence TO 0
Line 2 RECEIVE desired_value FROM (INTEGER) KEYBOARD
Line 3 FOR counter FROM 0 TO 9 DO
Line 4 IF age [counter] = desired_value THEN
Line 5 SET occurrence TO occurrence + 1
Line 6 END IF
Line 7 END FOR
Line 8 SEND "There were " & occurrence & " occurrences of " & desired_value TO DISPLAY