C Program to Calculate Average Using Arrays
Source Code to Calculate Average Using Arrays
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
printf("Enter the numbers of elements: ");
scanf("%d", &n);
while (n > 100 || n <= 0)
{
printf("Error! number should in range of (1 to 100).\n");
printf("Enter the number again: ");
scanf("%d", &n);
}
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
Output
Enter the numbers of elements: 6 1. Enter number: 45.3 2. Enter number: 67.5 3. Enter number: -45.6 4. Enter number: 20.34 5. Enter number: 33 6. Enter number: 45.6 Average = 27.69
This program takes the number of elements in the array and stores in the variable n.
Then, the for loop gets all the elements from the user and stores the sum of the entered numbers in sum.
Finally, the average is calculated by dividing sum by the number of elements n.
example C program to calculate the average of a set of numbers using arrays:
#include <stdio.h>
int main() {
int n, i;
float sum = 0.0, average;
printf("Enter the number of elements: ");
scanf("%d", &n);
float numbers[n]; // Declare an array of size n
printf("Enter %d numbers:\n", n);
// Loop to read n numbers from user input
for (i = 0; i < n; i++) {
scanf("%f", &numbers[i]);
sum += numbers[i]; // Calculate sum of all numbers
}
average = sum / n; // Calculate average of all numbers
printf("The average of the entered numbers is %.2f\n", average);
return 0;
}
In this program, we first ask the user to enter the number of elements (i.e. the size of the array). We then declare an array of size n
and use a loop to read n
numbers from the user input and store them in the array.
We also use a variable sum
to keep track of the sum of all the numbers in the array. After reading all the numbers, we calculate the average by dividing the sum by the number of elements in the array (n
).
Finally, we print the calculated average using the printf()
function.
Note: This program assumes that the user enters only valid numbers as input. You may want to add additional input validation checks if necessary.