find the totals of positive and negative integers

• 05-11-2004
noaksey
find the totals of positive and negative integers
Hey up everyone.

Right, this is whats baffling me. I want to read in a set of numbers (10), either positive or negative, and find the separate totals of both (if this is possible).

I have the following code:
Code:

```#include <stdio.h> int i,totpos,totneg; int main() {         for (i=0;i<10;i++)         {                 printf("Enter number %d...",i);                 scanf("%d",&number[i]);         }                 //                 printf("The totals of your positive numbers is: %d",totpos);         printf("The totals of your negative numbers is: %d",totneg);         return(0); }```
but I don't know how you add up, seprately, both the positive and negative integers! How would you distinguish between the two??

Any help would be much appriciated on this!

Cheers,
Chris.
• 05-11-2004
linuxdude
Quote:

(if this is possible).
Anything is possible first you don't have number declared, but for your functions you should test if they are positive or negative like this
Code:

```int totpos(int num){     static int total=0;     if(num<0)           return total;     else           return (total+=num); }```
and basically the same for negative numbers You need total to be static so it retains its value when you run it agian. Don't worry it won't be set to 0 the second or any other time you run it
• 05-11-2004
chrismiceli
you want to find the total of all the negative number, and the total of all the positive numbers?
Code:

```int array[10]; int x, negtot, postot; negtot = postot = 0; /* array is assigned */ for(x=0;x<10;x++) {     if(array[x] < 0)           negtot += array[x];     if(array[x] > 0)           postot += array[x];     /* don't have to worry about zero because it wouldn't affect the totals */ }```
• 05-11-2004
penney
Your number array must be declared: int number[10];

Then you can check for positive and negatives like:

if( number[i] >= 0 ) /* Your number is positive */
/* sum up your pos total here */
else /* Your number is negative */
/* sum up you neg total here */

And this check should go in your loop after you have read in the number.
• 05-11-2004
linuxdude
whoops i thought totpos was a function and so was totneg. Oh well. Ya'lls work
• 05-11-2004
quzah
You can also do it in a single loop. Hell, you can even do it while you initially read the value in. Here's the pseudocode. I'll leave it as an exercise to the origional poster:
Code:

```while we haven't read ten numbers     read a number     if the number is negative         add to negative numbers     otherwise         add to positive numbers print totals```
I can't make it any clearer than that, otherwise you'd have the source code for it.

Quzah.