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
- Read N (array size) from the user.
- Read N integers into the array one at a time.
- Walk the array once: accumulate
negsumfor negatives,posumfor positives, andtotalfor all elements. - Compute
average = total / Nand 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;scanfalready discards the newline on the next read.totalisfloat, so the divisiontotal / Nis floating-point, not integer division.- Zero elements are counted in the average but contribute to neither sum.
More C Programs
- Complete list of C programs
- Set up your C development environment
- Best online C compilers to run code instantly
Further reading: The C Programming Language by Kernighan & Ritchie — the definitive C reference.