In this post, we will learn how to calculate average using arrays in C Programming language.
This program will take multiple numbers as input from the user, and then calculate the average using arrays.
Average = Total Sum / Total no. of elements
So, without further ado, let’s begin this tutorial.
C Program To Calculate Average Using Arrays
// C Program To Calculate Average Using Arrays #include <stdio.h> int main(){ int i, n; float num[25], sum = 0.0, average; printf("Enter total no. of elements: "); scanf("%d", &n); while (n > 25 || n < 1){ printf("Please enter number in the range of 1 to 25"); scanf("%d", &n); } for (i = 0; i < n; ++i){ printf("%d. Enter a number: ", i + 1); scanf("%f", &num[i]); sum = sum + num[i]; } average = sum / n; printf("Average: %.2f", average); return 0; }
Output
Enter total no. of elements: 5
1. Enter a number: 7
2. Enter a number: 9
3. Enter a number: 5
4. Enter a number: 18
5. Enter a number: 15
Average: 10.80
How Does This Program Work ?
int i, n;
float num[25], sum = 0.0, average;
In this program, we have declared two int data type variables named i and n. We have also declared three float data type variables named num, sum and average.
printf("Enter total no. of elements: ");
scanf("%d", &n);
Then, the user is asked to enter the total no. of elements. This value will get stored in the n named variable.
while (n > 25 || n < 1){
printf("Please enter number in the range of 1 to 25");
scanf("%d", &n);
}
If the value of n is greater than 25 or less than 1, we ask the user to again enter the number in the range of 1 to 25.
for (i = 0; i < n; ++i){
printf("%d. Enter a number: ", i + 1);
scanf("%f", &num[i]);
sum = sum + num[i];
}
The elements entered by the user are stored in num[] array. Now, we calculate the sum of the elements using an array.
average = sum / n;
Average is calculated using the formula:
Average = Total Sum / Total no. of elements
printf("Average: %.2f", average);
Finally, the average is printed to the screen using printf() function. Here, we have used %.2f format specifier because we want to show the result only till 2 decimal places.
Conclusion
I hope after going through this post, you understand how to calculate average using arrays in C Programming language.
If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.
Also Read: