Write a C Program to Calculate the Average, Geometric and Harmonic Mean of n Elements in an Array

Understanding how to calculate the average, geometric mean, and harmonic mean is essential in statistics and data analysis. This tutorial explains how to write a C program to calculate the average, geometric and harmonic mean of n elements in an array, using simple loops and formulas.


C Program to Calculate Average, Geometric and Harmonic Mean

#include <stdio.h>
#include <math.h>

int main() {
int n, i;
float arr[100], sum = 0.0, product = 1.0, harmonicSum = 0.0;
float average, geometricMean, harmonicMean;

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

printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%f", &arr[i]);
sum += arr[i];
product *= arr[i];
harmonicSum += 1.0 / arr[i];
}

average = sum / n;
geometricMean = pow(product, 1.0/n);
harmonicMean = n / harmonicSum;

printf("Average = %.2f\n", average);
printf("Geometric Mean = %.2f\n", geometricMean);
printf("Harmonic Mean = %.2f\n", harmonicMean);

return 0;
}

Output Example

Enter the number of elements: 3  
Enter 3 elements:
2 4 8
Average = 4.67
Geometric Mean = 4.00
Harmonic Mean = 3.43

Explanation

  • Average (Arithmetic Mean): Sum of all values divided by the count.
  • Geometric Mean: nth root of the product of all values.
  • Harmonic Mean: n divided by the sum of reciprocals of values.

This C program uses loops and basic math functions to calculate all three means from a user-input array.


Use Cases

  • Academic performance analysis
  • Financial statistics
  • Engineering data interpretation

Knowing how to calculate average, geometric and harmonic mean of n elements in an array in C can help you in practical applications and technical interviews.

Previous Article

Write a Program to Find Maximum Element from 1-Dimensional Array in C

Next Article

Sort an Array in Ascending Order Using Insertion, Bubble, Selection, Merge, Quick, and Heap Sort in C

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨