Add the positive numbers and negative numbers into a array and calculate the sum of positive and negative numbers also average using c program




In this c program we are using concept of arrays in c. An array is a sequence of continuous memory locations that is used for storing values which can be accessed by increment array index. in general we can call an array is a collection of values of same type.

An array is declared as data type array name [size], that is "int array[23]" arrays using the memory locations which are sequential so lowest address have first element and highest address have last element of array.

Here this c program we are adding the user input into a array and so we can access the elements in the array in increment the array index by one. Now we just display the numbers in the array and we start checking each element that is positive, negative or zero. if it is positive it gets added to positive sum, if its negative it gets added to negative sum else its zero.

Finally we find the average of positive and negative sum.

===================================================================
#include <stdio.h>
 
#include <conio.h>
 
#define MAXSIZE 10      /* defines array size 10 */
 
void main()
 
{
 
   int array[MAXSIZE];
 
   int i, N, negsum=0, posum=0;
 
   float total=0.0, averg;
 
   clrscr();
 
   printf ("Enter the value of N\n");
 
   scanf("%d", &N);
 
   printf("Enter %d numbers (-ve, +ve and zero)\n", N);   /* enter the user input into the array we defined */
 
   for(i=0; i< N ; i++)
 
   {
 
	scanf("%d",&array[i]); 
 
	fflush(stdin);
 
   }
 
   printf("Input array elements\n");
 
   for(i=0; i< N ; i++)
 
   {
 
	printf("%+3d\n",array[i]);    /* prints the values inside of the array using 3 positions*/
 
   }
 
   /* Summing  begins */
 
   for(i=0; i< N ; i++)
 
   {
 
	if(array[i] < 0)
 
	{
 
	   negsum = negsum +  array[i];        /* if number is negative it gets added to negative sum */
	}
 
	else if(array[i] > 0)
 
	{
 
	  posum = posum + array[i];            /* if number is positive it gets added to positive sum */
 
	}
 
	else if( array[i] == 0)
 
	{
	   ;
	}
 
	total = total + array[i] ;
   }
 
   averg = total / N;
 
   printf("\nSum of all negative numbers    = %d\n",negsum);      /* calculating average */
 
   printf("Sum of all positive numbers    = %d\n", posum);
 
   printf("\nAverage of all input numbers   = %.2f\n", averg);   /* displays the output */
 
 
}        /*End of main()*/
==================================================================
OUTPUT of C program to read N integers (zero, +ve and -ve)
==================================================================
Enter the value of N
5
Enter 5 numbers (-ve, +ve and zero)
5
-3
0
-7
6
Input array elements
+5
-3
+0
-7
+6

Sum of all negative numbers = -10
Sum of all positive numbers = 11

Average of all input numbers = 0.20