Count occurrences
The Count Occurrences algorithm is used to find how many times a certain value appears in a list or array. It works by starting with a counter set to 0, then going through each item in the array one at a time. Each time the current item matches the condition or target value, the counter increases by 1. When the loop finishes, the counter contains the total number of matches. This method works for arrays of any size and can be applied to numbers, text, or other data types.
Example Code
names = ["Jane", "John", "Jess", "Jane", "Ava", "Jane"]
target = "Jane"
count = 0
for i in range(len(names)):
if names[i] == target:
count = count + 1
print(target, "appears", count, "times")
# Array storing names
names = ["Jane", "John", "Jess", "Jane", "Ava", "Jane"]
# Value we want to count
target = "Jane"
# Counter starts at 0
count = 0
# Loop through each position in the array
for i in range(len(names)):
# Check if the name at current position matches the target
if names[i] == target:
# If it matches, increase the counter by 1
count = count + 1
# Output the total count
print(target, "appears", count, "times")