Sum of Positive and Negative Numbers in an Array

Sum of positive and negative numbers in an array | Here we write a program to find the sum of positive and negative numbers in an array.

Program description:- Write a program to find the sum of all negative numbers and the sum of all positive numbers. Also, find the sum of the negative number and positive number.

C Program to Find Sum Positive & Negative Numbers in an Array

#include<stdio.h>
int main()
{
   int a[100], n, i, psum=0, nsum=0;

   printf("Enter array size [1-100]: ");
   scanf("%d",&n);
   printf("Enter %d elements: ",n);

   for(i=0; i<n; i++)
   {
     scanf("%d",&a[i]);
     if(a[i]<0) nsum += a[i];
     else psum += a[i];
   }

   printf("All Positive numbers sum: %d",psum);
   printf("\nAll Negative numbers sum: %d",nsum);
   printf("\nTotal sum = %d", psum+nsum);

   return 0;
}

Output for the different test-cases:-

Enter array size [1-100]: 5
Enter 5 elements: 9 -6 5 0 -2
All Positive numbers sum: 14
All Negative numbers sum: -8
Total sum = 6

Enter array size [1-100]: 5
Enter 5 elements: 1 2 -3 4 5
All Positive numbers sum: 12
All Negative numbers sum: -3
Total sum = 9

In this program to find sum of all positive number and the sum of all negative numbers we take two variables psum and nsum. The variable psum and nsum initialized with value zero. If the number is negative than number will be added with nsum else number is added with psum. By this way, we find psum and nsum values. After that, the total sum is given as psum+nsum. Finally, positive-sum, negative-sum and the total sum is displayed to the screen.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Similar C programming examples on Arrays

Leave a Reply