C Language Example - Calculate Average of Array Elements

C Language Examples

Use a for loop to iterate through the output elements, add them together to calculate the sum, then divide by the number of elements:

Example 1

#include <stdio.h> int main() { int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int sum, loop; float avg; sum = avg = 0; for(loop = 0; loop < 10; loop++) { sum = sum + array[loop]; } avg = (float)sum / loop; printf("The average is %.2f", avg); return 0; }

The output result is:

平均值为 4.50

User-defined input:

Example 2

#include <stdio.h> int main() { int n, i; float num[100], sum = 0.0, average; printf("Enter number of elements:"); scanf("%d", &n); while (n > 100 || n <= 0) { printf("Error! The number must be between 1 and 100.\n"); printf("Enter 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; }

The output result is:

输入元素个数: 4
1. 输入数字: 1
2. 输入数字: 2
3. 输入数字: 4
4. 输入数字: 8
平均值 = 3.75

C Language Examples

other extensions