Count occurrences

From Higher Computing Science
Jump to: navigation, search

Key points

  • Counting occurrences is an algorithm that checks an array for the presence of a particular item of data and adds to a count each time it is found. To do this, the user must be asked what they are searching for. A variable storing the number of times the item is found is set to zero. Each item in the array will be compared to the search term, and if the item is found, the total will be updated by one.

Information

Haggis implementation

 SET list TO [1,4,2,5,3]
 RECEIVE searchterm FROM (INTEGER) KEYBOARD
 SET total TO 0
 FOR counter FROM 0 TO 4 DO
   IF list[counter]=searchterm THEN
     SET total TO total + 1
  END IF
 END FOR
 SEND (STRING) searchterm & " appears in the array " & (STRING) total & " times" TO DISPLAY


Python implementation

Videos


Further information

Test yourself

Teaching resources