Skip to main content

Counters

A counter is a variable, usually an int, that tracks how many times something happens. Each time the event occurs, you increment (increase) or decrement (decrease) it.

Counters that Control Loops​

One pass through a loop is called an iteration. A counter can decide how many iterations run. It needs three parts:

  1. Start value: where the counter begins.
  2. Condition: checked before every iteration. The loop stops when it's false.
  3. Update: changes the counter each time. Without it, the condition never changes and the loop runs forever.

The update is usually +1 or -1, but it can be any step your logic needs.

Example 1: Counting from 1 to 5​

int count = 1; // start

while (count <= 5) // condition
{
Console.WriteLine(count);
count = count + 1; // update
}

Example 2: Beeping​

Programmers often start counters at 0. To run 5 times, use < instead of <=:

int beeps = 0;

while (beeps < 5) // runs for 0, 1, 2, 3, 4
{
Console.Beep();
beeps = beeps + 1; // same as beeps++
}

Tip: start = 1 with <= and start = 0 with < both run 5 times. Mixing them up causes an off-by-one error.