C++ | Counting positive,negative,even and odd numbers from array

Introduction

This is tutorial in c++ to count the +ve, -ve, even and odd numbers from arrays. The program below is given. The program below is extendable, look at the extending it section below. Go enjoy the program. Lets begin…..

Program to count the different numbers from array.

#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen
clrscr();
//declare variables as int.
int a[10],i,m;
//set count variables to zero
int n=0,p=0,e=0,o=0;
//input the numbers in array
for(i=0;i<5;i++)
{
cout<<“Enter the no: “;
cin>>a[i];
}
//start the counter
for(i=0;i<5;i++)
{
if(a[i]<0)
n++;
else
p++;
m=a[i]%2;
if(m==0)
e++;
else
o++;
}
//print the count
cout<<“————————-“<<endl;
cout<<“Even numbers are “<<e<<endl;
cout<<“Odd numbers are “<<o<<endl;
cout<<“+ve numbers are “<<p<<endl;
cout<<“-ve numbers are “<<n<<endl;
cout<<“————————-“<<endl;
//get character
getch();
}

Output

Enter the number
-1
Enter the number
2
Enter the number
3
Enter the number
-4
Enter the number
5
————————-
Even numbers are 2
Odd numbers are 3
+ve numbers are 3
-ve numbers are 2
————————-

How does it work

  1. You enter the number.
  2. The number is saved in respective array.
  3. The numbers from arrays are taken and tested if even or odd or +ve or -ve.
  4. The respective counters are increase.
  5. The counters are printed.

Extending it

The program can be extended by taking counter of prime numbers. Try it. Extend it.

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Add void main.
  3. Start program by first clearing the screen.
  4. Declare the variables as int (name them as you want.)
  5. Add the cout and cin of array.
  6. Setup the counter.
  7. Print the counter.

At the end

You learnt creating the C++ program of Counting the different types of numbers. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s