# How to perform Count and Toggle queries on Binary array in C++

In this post, we will learn how to perform toggle as well as count operations on a binary array in C++.

## Count and Toggle queries on Binary array C++

The binary array is an array in which all of its elements are either 1 or 0. Suppose we are given a binary array. We would like to perform some toggle and count operations on the elements of this array.

Operation 1:Toggle

Syntax: toggle(pos1,pos2);

Here , pos1 represents the starting position(index) and pos2 represents the end position(index) .These two will give the range on which the toggle operation is going to be performed.

The toggle operation changes the value from 0 to 1 or 1 to 0 within a given range.

Operation 2: Count

Syntax: count(pos1,pos2)

In above syntax , pos1 represents the starting position(index) and pos2 represents the end position(index) .These two will be used to specify a range within which we will like to count the number of 1’s after performing the toggle operations.

CODE to demonstrate toggle and count operations :

```//Count and Toggle Queries on a Binary Array

#include<iostream>
using namespace std;

void toggle(int pos1,int pos2,int arr1)
{ int i;
for(i=pos1;i<=pos2;i++)
{
if(arr1[i]==1)
arr1[i]=0;
else
arr1[i]=1;
}
}

void count(int pos1,int pos2,int arr2)
{
int i,c=0;                      // counter for counting number of 1s
for(i=pos1;i<=pos2;i++)
{
if(arr2[i]==1)
c++;
}
cout<<"COUNT ="<<c<<endl;

}
int main()
{
int arr={0,0,0,0,0};   // initially all the element of the array are 0s

// note changes made in an array once get stored automatically without providing the reference.......IMP

toggle(1,4,arr);  // change 1 into 0 or 0 into 1 from index 1 to index 4
toggle(1,3,arr);
count(2,4,arr);  // count all 1's within the range
toggle(1,2,arr);//change 1 into 0 or 0 into 1 from index 1 to index 2
count(1,5,arr); //count all 1's within the range
return 0;
}```

OUTPUT:

```COUNT =1

COUNT =3```