- 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 1’s in a sorted binary array in C++
In this tutorial, we will be discussing a program to find the 1’s in a sorted binary array.
For this we will be provided with an array containing only 1 and 0. Our task is to count the number of 1’s present in the array.
Example
#include <bits/stdc++.h> using namespace std; //returning the count of 1 int countOnes(bool arr[], int low, int high){ if (high >= low){ int mid = low + (high - low)/2; if ( (mid == high || arr[mid+1] == 0) && (arr[mid] == 1)) return mid+1; if (arr[mid] == 1) return countOnes(arr, (mid + 1), high); return countOnes(arr, low, (mid -1)); } return 0; } int main(){ bool arr[] = {1, 1, 1, 1, 0, 0, 0}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Count of 1's in given array is " << countOnes(arr, 0, n-1); return 0; }
Output
Count of 1's in given array is 4
- Related Articles
- Count the number of 1’s and 0’s in a binary array using STL in C++
- Count subarrays consisting of only 0’s and only 1’s in a binary array in C++
- Absolute distinct count in a sorted array in C++?
- Find the index of first 1 in a sorted array of 0's and 1's in C++
- Count number of binary strings without consecutive 1's in C
- Given a sorted array of 0’s and 1’s, find the transition point of the array in C++
- Count smaller elements in sorted array in C++
- Program to Count number of binary strings without consecutive 1’s in C/C++?
- Count Binary String without Consecutive 1's
- Absolute distinct count in a sorted array?
- Count number of binary strings of length N having only 0’s and 1’s in C++
- C/C++ Program to Count number of binary strings without consecutive 1’s?
- Count number of occurrences (or frequency) in a sorted array in C++
- Find the Rotation Count in Rotated Sorted array in C++
- Finding maximum number of consecutive 1's in a binary array in JavaScript

Advertisements