adplus-dvertising

C program to calculate sum and average of an array

frame-decoration

C program to calculate sum and average of an array

Problem Description

This C program finds the sum and average of an array. First it asks the user to input the desired number of elements in the array. Then, it ask the user to input each element of the array and display the sum and average of entered elements.

C program to calculate sum and average of an array - Source code
     
                
  #include <stdio.h>

int main()
{
    int Arr[50];
    int n, i, sum = 0;
    float average;

    printf("Enter the number of elements you want in Array : ");
    scanf("%d", &n);

    for (i = 0; i < n; i++)
    {
        printf("Enter element %d : ", i + 1);
        scanf("%d", &Arr[i]);
        sum = sum + Arr[i];
    }

    average = (float)sum/n;

    printf("\nThe sum of the elements array is : %d", sum);
    printf("\nThe average of the elements array is : %0.2f", average);

    return 0;
}
     
      

Program Output

Enter the number of elements you want in Array : 6
Enter element 1 : 23
Enter element 2 : 54
Enter element 3 : 69
Enter element 4 : 25
Enter element 5 : 12
Enter element 6 : 5

The sum of the elements array is : 188
The average of the elements array is : 31.33

Program Explanation

1. First the program user is asked to enter the value of n, which is the desired number of elements in the array.

2. Then each number is saved in array using a scanf statement inside a for loop. Note that the sum of array is also calculated in the same for loop.

3. To calculate the average of the array, (sum/no of elements) mathematical formula is used. Here important thing to note that is sum variable is type casted to float type in order to print the average as float.

4. At last, both sum and average are displayed as output of the program.