- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count the number of 1’s and 0’s in a binary array using STL in C++
In this tutorial, we will be discussing a program to count the number of 1’s and 0’s in a binary array using STL in C++.
For this we will be provided with an array. Our task is to count the number of 0’s and 1’s present in the array.
Example
#include <bits/stdc++.h> using namespace std; // checking if element is 1 or not bool isOne(int i){ if (i == 1) return true; else return false; } 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; }
Output
1's: 3 0's: 4
- Related Articles
- Count subarrays consisting of only 0’s and only 1’s in a binary array in C++
- Count number of binary strings of length N having only 0’s and 1’s in C++
- Count subarrays with equal number of 1’s and 0’s in C++
- Count 1’s in a sorted binary array in C++
- Largest number with binary representation is m 1’s and m-1 0’s in C++
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- Count number of binary strings without consecutive 1's in C
- Segregate 0’s and 1’s in an array list using Python?
- 1’s and 2’s complement of a Binary Number?
- Given a sorted array of 0’s and 1’s, find the transition point of the array in C++
- Sort an arrays of 0’s, 1’s and 2’s using C++
- Program to Count number of binary strings without consecutive 1’s in C/C++?
- Maximum 0’s between two immediate 1’s in binary representation in C++
- Find the index of first 1 in a sorted array of 0's and 1's in C++
- C/C++ Program to Count number of binary strings without consecutive 1’s?

Advertisements