The arithmetic mean is the sum of all values divided by the number of values. In C, use a floating-point calculation when the average may contain a fractional part.
#include <stdio.h>
int main(void) {
double first = 12.0;
double second = 15.0;
double average = (first + second) / 2.0;
printf("Average = %.2f\n", average);
return 0;
}
#include <stdio.h>
int main(void) {
double first;
double second;
printf("Enter two numbers: ");
if (scanf("%lf %lf", &first, &second) != 2) {
printf("Invalid input.\n");
return 1;
}
printf("Average = %.2f\n", (first + second) / 2.0);
return 0;
}
#include <stdio.h>
int main(void) {
double values[] = {10.0, 12.5, 8.5, 14.0};
size_t count = sizeof values / sizeof values[0];
double sum = 0.0;
for (size_t i = 0; i < count; i++) {
sum += values[i];
}
printf("Average = %.2f\n", sum / count);
return 0;
}
For an array, derive the element count from the array itself instead of hard-coding the divisor.
The original page included a weighted-average example, which is different from an ordinary arithmetic mean because each value contributes according to its weight.
#include <stdio.h>
int main(void) {
int values[] = {70, 80, 90};
int weights[] = {1, 2, 3};
size_t count = sizeof values / sizeof values[0];
int weighted_sum = 0;
int total_weight = 0;
for (size_t i = 0; i < count; i++) {
weighted_sum += values[i] * weights[i];
total_weight += weights[i];
}
double weighted_average =
(double)weighted_sum / total_weight;
printf("Weighted Average: %.2f\n", weighted_average);
return 0;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| md raihan | 31-07-2016 |
| Thank u so much.....for given us a simple code that complete my assignment..so thank u....so much..sir.. | |
| g v divyaklakshmi | 30-08-2016 |
| thank u very much . its is very use full for us in right time | |
| that guy | 31-12-2016 |
| Thank you so much. it helps so much for my project. But there are still errors, can u help me with that? | |
| riddhi | 03-10-2017 |
| how to find avg in simple method | |