C program to Calculate Average of an Array

Write a C program to calculate average of an array using for loop. In this c example, the for loop iterate all array elements and calculate the sum. Next, we calculate the average by dividing the sum with array size.

#include <stdio.h>

int main()
{
	int Size, i, sum = 0;
	float avg = 0;

	printf("Please Enter the Array size = ");
	scanf("%d", &Size);

	int arr[Size];

	printf("Enter the Array Elements : ");
	for (i = 0; i < Size; i++)
	{
		scanf("%d", &arr[i]);
	}

	for (i = 0; i < Size; i++)
	{
		sum = sum + arr[i];
	}

	avg = (float)sum / Size;

	printf("\nThe Sum of Array Elements     = %d\n", sum);
	printf("\nThe Average of Array Elements = %.2f\n", avg);
}
Please Enter the Array size = 10
Enter the Array Elements : 22 44 66 88 99 111 123 133 144 155

The Sum of Array Elements     = 985

The Average of Array Elements = 98.50

In this c array average example, we removed the extra for loop. Then, we performed the addition while inserting or reading the array elements.

#include <stdio.h>

int main()
{
	int Size, sum = 0;
	float avg = 0;

	printf("Please Enter the Array size = ");
	scanf("%d", &Size);

	int arr[Size];

	printf("Enter the Array Elements : ");
	for (int i = 0; i < Size; i++)
	{
		scanf("%d", &arr[i]);
		sum = sum + arr[i];
	}

	avg = (float)sum / Size;

	printf("\nThe Sum of Array Elements     = %d\n", sum);
	printf("\nThe Average of Array Elements = %.2f\n", avg);
}
C program to Calculate Average of an Array 2

C program to Calculate Average of an Array using a while loop

#include <stdio.h>

int main()
{
	int Size, sum = 0;
	float avg = 0;

	printf("Please Enter the size = ");
	scanf("%d", &Size);

	int arr[Size];

	printf("Enter the Elements : ");
	int i = 0; 
	while(i < Size)
	{
		scanf("%d", &arr[i]);
		sum = sum + arr[i];
		i++;
	}

	avg = (float)sum / Size;

	printf("\nThe Sum of Array Elements     = %d\n", sum);
	printf("\nThe Average of Array Elements = %.2f\n", avg);
}
Please Enter the size = 7
Enter the Elements : 19 29 39 49 59 79 89

The Sum of Array Elements     = 363

The Average of Array Elements = 51.86

In this c program, the arrayAverage function accepts the array and its size and calculates the average of elements.

#include <stdio.h>

float arrayAverage(int arr[], int Size)
{
	int sum = 0;
	float avg = 0;

	for (int i = 0; i < Size; i++)
	{
		sum = sum + arr[i];
	}

	printf("\nThe Sum     = %d\n", sum);

	avg = (float)sum / Size;
	return avg;
}

int main()
{
	int Size;

	printf("Please Enter the size = ");
	scanf("%d", &Size);

	int arr[Size];

	printf("Enter the Elements : ");
	for (int i = 0; i < Size; i++)
	{
		scanf("%d", &arr[i]);
	}

	float avg = arrayAverage(arr, Size);
	
	printf("\nThe Average = %.2f\n", avg);
}
Please Enter the size = 8
Enter the Elements : 22 99 66 44 567 65 11 67

The Sum     = 941

The Average = 117.62