C Program To Find The Sum & Average

C Program to Find Sum and Average of an Array

This program reads N integers (positive, negative, and zero) into an array and computes three values: the sum of negatives, the sum of positives, and the average of all elements.

Algorithm

  1. Read N (array size) from the user.
  2. Read N integers into the array one at a time.
  3. Walk the array once: accumulate negsum for negatives, posum for positives, and total for all elements.
  4. Compute average = total / N and print the three results.

C Program

#include <stdio.h>
#define MAXSIZE 10

int main(void)
{
    int array[MAXSIZE];
    int i, N, negsum = 0, posum = 0;
    float total = 0.0f, averg;

    printf("Enter the value of N (1-%d): ", MAXSIZE);
    scanf("%d", &N);
    if (N < 1 || N > MAXSIZE) {
        printf("N must be between 1 and %d.\n", MAXSIZE);
        return 1;
    }

    printf("Enter %d numbers (-ve, +ve, and zero): ", N);
    for (i = 0; i < N; i++)
        scanf("%d", &array[i]);

    printf("\nInput array elements:\n");
    for (i = 0; i < N; i++)
        printf("  %+3d\n", array[i]);

    for (i = 0; i < N; i++) {
        if (array[i] < 0)
            negsum += array[i];
        else if (array[i] > 0)
            posum += array[i];
        total += array[i];
    }

    averg = total / N;
    printf("\nSum of all negative numbers  = %d\n", negsum);
    printf("Sum of all positive numbers  = %d\n", posum);
    printf("Average of all input numbers = %.2f\n", averg);

    return 0;
}

Sample Output

Enter the value of N (1-10): 5
Enter 5 numbers (-ve, +ve, and zero): 3 -2 0 7 -5

Input array elements:
   +3
   -2
   +0
   +7
   -5

Sum of all negative numbers  = -7
Sum of all positive numbers  = 10
Average of all input numbers = 0.60

Key Points

  • Input validation keeps N within array bounds — no buffer overrun possible.
  • fflush(stdin) removed: flushing an input stream is undefined behavior in standard C; scanf already discards the newline on the next read.
  • total is float, so the division total / N is floating-point, not integer division.
  • Zero elements are counted in the average but contribute to neither sum.

More C Programs

Further reading: The C Programming Language by Kernighan & Ritchie — the definitive C reference.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>