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:
- Start value: where the counter begins.
- Condition: checked before every iteration. The loop stops when it's
false. - 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 = 1with<=andstart = 0with<both run 5 times. Mixing them up causes an off-by-one error.