Counters

There are a number of times in computer programming where the user needs to determine the number of times a certain event occurs.

Examples:

  • Counting the number of times a person enters a number (in order to find the average)
  • Determining how many rolls of two dice were needed before a 6 was rolled
  • Counting the number of times “heads” was flipped when flipping a coin 100 times.

The counter statement in programming looks like:

counter = counter +1

or

c = c+ 1

Even though this is not a valid equation in Mathematics, it is completely valid in programming.
The equal sign is interpreted as “is replaced by”.

Therefore    c = c +1  forces the computer to:

  • go get the value of c from memory
  • add 1 to the value of c
  • re-store the value of c in the same memory location

i.e.  it takes the current value of ‘c’ in memory and increases it by one.

The counter statement is placed in a program immediately after the process that is being counted.

Totals

The total statement is very similar to the counter statement, but instead of increasing the counter variable by 1, the total statement increases the total by whatever needs to be added to the total.

The format of the total statement is:

total = total + num   (if the total is to be increased by the value of num)

agetotal = agetotal + age

Example Program: The following program will allow the user to enter numbers one after another until a zero is entered.  The program will find the average of all the numbers that were entered.

dim total as integer, numcount as integer, num as integer, average as single

total = 0

numcount = 0

do

input “Enter a number: “, num

if num = 0 then exit do

total = total + num

numcount = numcount +1

loop

average = total / numcount

print  using “the average of the numbers is ###.#”; average

author avatar
William Anderson (Schoolworkhelper Editorial Team)
William completed his Bachelor of Science and Master of Arts in 2013. He current serves as a lecturer, tutor and freelance writer. In his spare time, he enjoys reading, walking his dog and parasailing. Article last reviewed: 2022 | St. Rosemary Institution © 2010-2024 | Creative Commons 4.0

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment