Counting
Counting is the second of the two common loop tasks. It has the same three parts as summing, with one difference at the centre. Start a variable at 0…
The counter pattern
Counting is the second of the two common loop tasks. It has the same three parts as summing, with one difference at the centre.Start a variable at 0 before the loop. Visit every item. When an item is worth counting, add ONE. Summing adds the item itself; counting adds 1 no matter how big the item is.
Counting factors
Write a function that accepts an integer parameter n and returns the number of factors of n.The loop tries every candidate from 1 up to n, and n % i == 0 asks whether i divides n exactly. Note the range: it has to reach n itself, because n is always a factor of n.
Counting letters
Given a string, count the number of occurrences of the letter "A" or "a". Since a string is a sequence of characters, the loop can walk the letters directly.