Write a C program to find the sum and average of array elements

Description: Take 5 numbers and store them in an array. Print the sum and the average.

Hint:

  • Use a loop to read each element and add it to a sum variable.

C program to find the sum and average of an array

#include <stdio.h>

int main(void) {
    int a[5], sum = 0;

    printf("Enter 5 numbers: ");
    for (int i = 0; i < 5; i++) {
        scanf("%d", &a[i]);
        sum += a[i];
    }
    printf("Sum = %d\n", sum);
    printf("Average = %.2f\n", sum / 5.0);
    return 0;
}

Output:

Output of the above program is

Enter 5 numbers: 10
20
30
40
55
Sum = 155
Average = 31.00

How it works

  • The loop reads the numbers into a[0] to a[4], and adds them to sum.
  • We divide by 5.0 to get the decimal average.

Read C Arrays.


Learn more about the similar topics:
Tutorials
C Arrays
C Two Dimensional Arrays
C Passing Arrays to Functions
C Strings
C String Input and Output
C String Functions
C strlen() Function
Exercises & Assignments
Write a C program to find the sum and average of array elements
Write a C program to find the largest element in an array
Write a C program to print the elements of an array in reverse order
Write a C program to sort an array using bubble sort
Write a C program to search an element in an array
Write a C program to add two matrices
Write a C program to find the length of a string without using strlen
Interview Questions & Answers
What is an array in C?
How is a string stored in C?
How to reverse a string in C?
What is the difference between memcpy() and strcpy() in C?