# What are counter variables and how do i implement them in c++?

My friend used counter variables to solve a question and im wondering how he did it. What does it do and how do I implement them in c++?

@spaciouscoder7
Counter variable is simply a variable which counts a something specific.

Let’s say we have an array such as [ 0, 1, 1, 0, 1]. If we want to find total number of ones in the given array, we would need to iterate over the whole array and keep track of number of 1’s we encounter.

Let’s take a variable to count number of instances of 1 as;

``````int count=0;
``````

We have initialized it as zero here but the initial value can be changed as needed.
Now while iterating over the array;

• First element is 0: As its not a 1, we simple continue. Value of counter variable, (count=0).

• Second is 1: We encountered a 1, therefore we increase the counter by +1 as,

``````count++;
``````

or

``````count=count+1;
``````

Currently value of (count=1).

• Third is 1: We encounter another 1, so counter is incremented again by +1.
Now, (count=2).

• Fourth is 0: We do nothing. Value of counter is still 2.

• Fifth is 1: Increase counter value by +1. Current value is now, count=3.

Finally, total number of 1’s contained in the above array is three.

This is the way a counter variable is generally used.