Skip to content
Related Articles

Related Articles

Count the number of 1’s and 0’s in a binary array using STL in C++ ?
  • Last Updated : 01 Apr, 2019

Given a binary array, the task is to count the number of 1’s and 0’s in this array using STL in C++.

Examples:

Input:  arr[] = {1, 0, 0, 1, 0, 0, 1}
Output: 1's = 3, 0's = 4

Input:  arr[] = {1, 1, 1, 1, 0, 0, 1}
Output: 1's = 5, 0's = 2

Approach: We can count the same using count_if() function present in the STL of C++.

Syntax:

count_if(lower_bound, upper_bound, filter_function)

where filter_function is a condition
which filters out elements.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to Count
// the number of 1's and 0's
// in a binary array
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to check
// if bit is 1 or not
bool isOne(int i)
{
    if (i == 1)
        return true;
    else
        return false;
}
  
// Driver Code
int main()
{
  
    int a[] = { 1, 0, 0, 1, 0, 0, 1 };
  
    int n = sizeof(a) / sizeof(a[0]);
  
    int count_of_one = count_if(a, a + n, isOne);
  
    cout << "1's: " << count_of_one << endl;
    cout << "0's: " << (n - count_of_one) << endl;
  
    return 0;
}

chevron_right


Output:

1's: 3
0's: 4

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :