In this example, we will learn a C++ program to count positive, negative, and zeros in an array. This program takes the maximum number for an array from the user and counts similar numbers.
Example: C++ program to count positive negative and zeros
Here is the code to take maximum array values from the user. Programs count their zeros, positive and negative numbers.
//C++ program to count positive, negative and zeros
#include<iostream>
using namespace std;
int main()
{
int countPositive=0, countNegative=0, countZero=0, arr[50], i, number;
cout<<"Input maximum numbers to enter 0-50: ";
cin>>number;
for(i=0; i<number; i++)
{
cin>>arr[i];
}
for(i=0; i<number; i++)
{
if(arr[i]<0)
{
countNegative++;
}
else if(arr[i]==0)
{
countZero++;
}
else
{
countPositive++;
}
}
cout<<"Positive numbers are: "<<countPositive<<endl;
cout<<"Negative numbers are: "<<countNegative<<endl;
cout<<"Total zeros are: "<<countZero<<endl;
return 0;
}
Output
Description and working of this program
- Initialize 5 variables and named it “countPositive=0”, “countNegative=0”, “countZero=0”, “i” and “number”.
- Initialize array named it “arr[50]”.
- Take the Maximum length value of an array from the user and store it in the “number” variable.
- Initialize two for loops one to store array values to each index and the other is used to move at each index.
- If the array values are greater than 0. Increments in countPositive.
- If the array values less than 0. Increments in countNegative.
- And if the array value is equal to zero. Increments in countZero.
- After that result is displayed on the screen.