C Program to Calculate Sum & Average of an Array


  1. #include  <stdio.h>
  2. #define MAXSIZE 10
  3. 
    
  4. void main()
  5. {
  6.     int array[MAXSIZE];
  7.     int i, num, negative_sum = 0, positive_sum = 0;
  8.     float total = 0.0, average;
  9. 
    
  10.     printf ("Enter the value of N \n");
  11.     scanf("%d", &num);
  12.     printf("Enter %d numbers (-ve, +ve and zero) \n", num);
  13.     for (i = 0; i < num; i++)
  14.     {
  15.         scanf("%d", &array[i]);
  16.     }
  17.     printf("Input array elements \n");
  18.     for (i = 0; i < num; i++)
  19.     {
  20.         printf("%+3d\n", array[i]);
  21.     }
  22.     /*  Summation starts */
  23.     for (i = 0; i < num; i++)
  24.     {
  25.         if (array[i] < 0)
  26.         {
  27.             negative_sum = negative_sum + array[i];
  28.         }
  29.         else if (array[i] > 0)
  30.         {
  31.             positive_sum = positive_sum + array[i];
  32.         }
  33.         else if (array[i] == 0)
  34.         {
  35.             ;
  36.         }
  37.         total = total + array[i] ;
  38.     }
  39.     average = total / num;
  40.     printf("\n Sum of all negative numbers =  %d\n", negative_sum);
  41.     printf("Sum of all positive numbers =  %d\n", positive_sum);
  42.     printf("\n Average of all input numbers =  %.2f\n", average);
  43. }

 

output:

Enter the value of N
10
Enter 10 numbers (-ve, +ve and zero)
-8
9
-100
-80
90
45
-23
-1
0
16
Input array elements
 -8
 +9
-100
-80
+90
+45
-23
 -1
 +0
+16
 
Sum of all negative numbers =  -212
Sum of all positive numbers =  160
 
Average of all input numbers =  -5.20