C++ Program to Count Positive and Negative Numbers in an Array
Last Updated :
27 Feb, 2023
Given an array arr of integers of the size of N, our task is to find the count of positive numbers and negative numbers in the array.
Examples:
Input: arr[] = [-9,7,-5,3,2]
Output: Positive elements = 3, Negative elements = 2
Input: arr[] = [5,4,-2,-1,-7]
Output: Positive elements = 2, Negative elements = 3
Approach:
- Traverse the elements in the array one by one.
- Find the element positive or not positive by using the condition element >=0. If the condition is satisfied increase the p_count.
- Remove the p_count from the total number of elements to get count negative numbers in the array.
- Print the positive and negative numbers count.
Example:
C++
// C++ program to find the count of positive
// and negative integers in an array
#include<bits/stdc++.h>
using namespace std;
//function to calculate the positive numbers in an array
int CountPositive(int arr[],int n){
int p_count = 0;
for(int i =0;i<n;i++){
if (arr[i]>=0){
p_count++;
}
}
return p_count;
}
//Function to print the array
void printArray(int arr[],int n){
cout<<"Array: ";
for(int i = 0; i<n; i++){
cout<<arr[i]<<" ";
}
cout<<"\n";
}
// Driver program
int main()
{
int arr[] = {-9,7,-5,3,2 };
int n;
n = sizeof(arr) / sizeof(arr[0]);
printArray(arr, n);
int p_count = CountPositive(arr,n);
cout<<"Count of Positive elements = "<<p_count<<", ";
cout<<"Count of Negative elements = "<<n - p_count;
return 0;
}
OutputArray: -9 7 -5 3 2
Count of Positive elements = 3, Count of Negative elements = 2
Time complexity: O(n)
Auxiliary space: O(1)
Method: Using Recursion
C++
// C++ program to find the count of positive
// and negative integers in an array
#include<bits/stdc++.h>
using namespace std;
//Defining recursive function to calculate no of positive in an array
int CountPositive(int begin,int arr[],int n,int pos_count){
if (begin==n) //base condition
return pos_count;
if (arr[begin]>=0) //checking whether no is positive or not
pos_count++;
return CountPositive(begin+1,arr,n,pos_count); //recursive calling
}
//Function to print the array
void printArray(int arr[],int n){
cout<<"Array: ";
for(int i = 0; i<n; i++){
cout<<arr[i]<<" ";
}
cout<<"\n";
}
// Driver program
int main()
{
int arr[] = {-9,7,-5,3,2 };
int n;
n = sizeof(arr) / sizeof(arr[0]);
printArray(arr, n);
int p_count = CountPositive(0,arr,n,0); //calling recursive function
cout<<"Count of Positive elements = "<<p_count<<", ";
cout<<"Count of Negative elements = "<<n - p_count;
return 0;
}
OutputArray: -9 7 -5 3 2
Count of Positive elements = 3, Count of Negative elements = 2
Time complexity: O(n)
Auxiliary space: O(n)
Another approach using C++ Standard Template Library (STL) and 'count_if()'function:
C++
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {-9,7,-5,3,2};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"Array: ";
for(int i = 0; i<n; i++){
cout<<arr[i]<<" ";
}
cout<<"\n";
// use count_if function to count positive and negative numbers
int pos_count = count_if(arr, arr + n, [](int x) { return x >= 0; });
int neg_count = count_if(arr, arr + n, [](int x) { return x < 0; });
// print the counts
cout << "Count of Positive elements ="<< pos_count<<", ";
cout << "Count of Negative elements = " << neg_count;
return 0;
}
OutputArray: -9 7 -5 3 2
Count of Positive elements =3, Count of Negative elements = 2
Time complexity: O(n)
Auxiliary space: O(n)
Another Efficient Approach ( Using binary search ) :
- If the array is not sorted , then first sort the array.
- Using Binary Search to get the last index of negative number in the sorted array.
- Initialize index as last index of negative number to -1 in array because ,if there is no negative number in the array , then it will return -1 as last index of negative number.
- Count of negative numbers will be ' index +1 ' because we are using 0-based indexing
- Count of positive numbers will be 'count of total numbers - count of negative numbers in the array .
- Print final answer .
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find last index of negative number
// in the sorted array
int BinarySearch(int *arr, int n)
{
int l = 0, r = n-1, index = -1;// Initialize index as -1 initially
while(l <= r)
{
int mid = (l + r) / 2;
// if arr[mid] is negative , then we will not search
// in the range [l,mid-1] because last index of negative
//number will be in the range [mid,r] in the sorted array
if(arr[mid]<0)
{
l = mid + 1;
index=mid;// updating rightmost index of
// negative number every time in the sorted array
}
else
{
r = mid - 1;
}
}
// return last index of negative number
return index;
}
// Function to print array elements
void printArray(int *arr,int n)
{
cout<<"Array: ";
for(int i = 0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
// Drive Code
int main()
{
int arr[] = {-9,7,-5,3,2 };
int n = sizeof(arr) / sizeof(arr[0]);
printArray(arr, n);
//sorting array for binary search
sort(arr,arr+n);
int neg_count = BinarySearch(arr, n)+1;
int pos_count = n - neg_count;
// print the counts
cout << "Count of Positive elements = "<< pos_count<<", ";
cout << "Count of Negative elements = " << neg_count<<endl;
return 0;
}
// This code is contributed by nikhilsainiofficial546
OutputArray: -9 7 -5 3 2
Count of Positive elements = 3, Count of Negative elements = 2
Time complexity: O(n*log2n)
Auxiliary space: O(1)
Similar Reads
JavaScript Program to Count Positive and Negative Numbers in an Array Given an array of numbers. Write a JavaScript program to count positive and negative numbers in an array.Example:Input: numbers_array1= [10,20, -1,22,99,20, -9]Output: positive no's=5, negative no's =2Input: numbers_array2= [-121, - 78, -13, 54, -23]Output: positive no's=1, negative no's=4Brute Forc
2 min read
Count number of Inversion in a Binary Array Given a Binary Array arr[], the task is to count the number of inversions in it. The number of inversions in an array is the number of pairs of indices i, j such that i < j and a[i] > a[j]. Examples: Input: arr[] = {1, 0, 1, 0, 0, 1, 0}Output: 8Explanation: Pairs of the index (i, j) are (0, 1)
4 min read
Count number of strictly increasing and decreasing subarrays Given an array arr[] of size N, the task is to find the number of strictly increasing and decreasing subarrays.Examples: Input: arr[] = { 80, 50, 60, 70, 40, 40 } Output: 9 8Explanation: The increasing subarrays are: {80}, {50}, {60}, {70}, {40}, {40}, {50, 60}, {60, 70} and {50, 60, 70}. The decrea
9 min read
Rearrange given array to obtain positive prefix sums at exactly X indices Given an array arr[] consisting of N integers whose absolute values are distinct and an integer K, the task is to find such an arrangement of the given array by the following operations, such that it has positive prefix sum at exactly K places: Choose two integers i, j and swap the values of the ele
8 min read
Menu driven program in C++ to perform various basic operations on array Prerequisite: Switch Statement in C/C++, Functions in C/C++, Loops in C and C++, C/C++ do-while loop with Examples Write a menu-driven program to perform below various basic operations in the array: Print all the even values in the array.Print all the odd values in the array.Sum & average of ele
5 min read
Noble integers in an array (count of greater elements is equal to value) Given an array arr[], find a Noble integer in it. An integer x is said to be Noble in arr[] if the number of integers greater than x is equal to x. If there are many Noble integers, return any of them. If there is no, then return -1. Examples : Input : [7, 3, 16, 10] Output : 3 Number of integers gr
15+ min read
Count ways to obtain triplets with positive product consisting of at most one negative element Given an array arr[] of size N (1 ? N ? 105), the task is to find the number of ways to select triplet i, j, and k such that i < j < k and the product arr[i] * arr[j] * arr[k] is positive. Note: Each triplet can consist of at most one negative element. Examples: Input: arr[] = {2, 5, -9, -3, 6
5 min read
Create Array following condition such that exactly M prefixes have positive Sum You are given two integers N and M (M ⤠N), the task is to create an array of length N following the below-given conditions. |Ai| = i, Formally, A[i] will be either -i or i.Exactly M prefix arrays should be there, Such that sum of each prefix array should be greater than zero. Note: If there are mul
10 min read
Queries to calculate sum by alternating signs of array elements in a given range Given an array arr[] of size N and a 2D array Q[][], consisting of queries of the following two types: 1 X Val: Update arr[X] = Val.2 L R: Find the sum of array elements with alternating signs in the range [L, R]. Examples: Input: arr[] = { 1, 2, 3, 4 }, Q[][] = { { 2, 0, 3 }, { 1, 1, 5 }, { 2, 1, 2
15+ min read
Array algorithms in C++ STL (all_of, any_of, none_of, copy_n and iota) From C++11 onwards, some new and interesting algorithms are added in STL of C++. These algorithms operate on an array and are useful in saving time during coding and hence useful in competitive programming as well. all_of() This function operates on whole range of array elements and can save time to
4 min read