Array Members Counter

Status
Not open for further replies.

Baljeet

Member
Jan 31, 2011
76
0
Hello CC Members ..:D

Today I'd Like to Show You How to Make a Simple Program that will Count and tell us How many Positive and Negative Members are there in an Array ..

So,

Code:
#include <iostream.h>
int main()
{
    const int m=7, A[m]={6,-2,-9,4,7,3,-5};
    int i,p,n;

First, We Declare the Variables ..
We Declare and Initialize an Array with 7 members on it ..The Members are {6,-2,-9,4,7,3,-5} .. Our Counter will Count these Members and Will Tell us How Many of them are Positive and How Many Negative .. We also declare the Variables "i,p,n" .. (p for positive members and n for negative members)
Code:
p=0;
n=0;
    
    for (i=0;i<m;i++)
            if (A[i]<0)
                 n=n+1;
            else
                 p=p+1;

We Initialize the "p" and the "n" 0 .. Because the Counter will Start to Count from 0 ..

Now, We Make a Loop that Will go Through each Array Member Starting from 0 (A0 = the first Array Member) till m [m=7 (the last member A6)] increasing the "i" for one (i++) ..
The Counter Will Look at each Member so, if the Member is Smaller than 0 (that means the Member is a Negative Number .. so the "n" Counter will increase for 1 ..) or if it isn't, the "p" Counter will increase for 1 ..

The Loop Will Continue to Count till the Last Array Member .. and When it Comes to the Last One .. it Will Tell us How Many Positive and Negative Members are there..

..

Code:
cout << "\nPositive Array Members p="
         << p
         << "\n";
    cout << "\nNegative Array Members n="
         << n
         << "\n\n";

Now, The Part Where we print "p" and "n" ..
Code:
"\n"
means New Line .. so the output in the console application will start from the second line .. than after printing "p" there's another New Line and than the the "n" will be printed too ..

..

Code:
         system ("pause");
         
         return 0;
         }

Now, We add a
Code:
system("pause")
to Make the Console Application Window stay up .. otherwise if we don't add this Part in our Code.. the Console Application Window will just appear and than disappear again ..

..

Finally the Code will Look Like the Following:


Code:
#include <iostream.h>
int main()
{
    const int m=7, A[m]={6,-2,-9,4,7,3,-5};
    int i,p,n;
    p=0;
    n=0;
    
    for (i=0;i<m;i++)
            if (A[i]<0)
                 n=n+1;
            else
                 p=p+1;
                 
    cout << "\nPositive Array Members p="
         << p
         << "\n";
    cout << "\nNegative Array Members n="
         << n
         << "\n\n";
         
         system ("pause");
         
         return 0;
         }

And the Console Application:

attachment.php



Thanks,

Egz0N..

All Credits goes to one who really made this...
 
Status
Not open for further replies.

Users who are viewing this thread

Top