Print the Mean
In this final step, we'll refactor the code to create a function for calculating and printing the mean, making our program more modular and readable.
Open the existing file:
cd ~/project
nano mean_calculation.c
Update the code with a dedicated function for mean calculation:
#include <stdio.h>
#define MAX_SIZE 100
// Function to calculate and print mean
void calculateMean(int numbers[], int count) {
if (count <= 0) {
printf("Error: No numbers to calculate mean.\n");
return;
}
int sum = 0;
float mean;
// Calculate sum
for (int i = 0; i < count; i++) {
sum += numbers[i];
}
// Calculate mean
mean = (float)sum / count;
// Print detailed statistics
printf("\nStatistics:\n");
printf("Number of elements: %d\n", count);
printf("Sum of numbers: %d\n", sum);
printf("Mean of numbers: %.2f\n", mean);
}
int main() {
int numbers[MAX_SIZE];
int count;
// Prompt user for the number of elements
printf("Enter the number of elements (max %d): ", MAX_SIZE);
scanf("%d", &count);
// Input validation
if (count <= 0 || count > MAX_SIZE) {
printf("Invalid number of elements!\n");
return 1;
}
// Read numbers into the array
printf("Enter %d numbers:\n", count);
for (int i = 0; i < count; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &numbers[i]);
}
// Print the entered numbers
printf("\nEntered numbers are:\n");
for (int i = 0; i < count; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// Calculate and print mean
calculateMean(numbers, count);
return 0;
}
Compile the program:
gcc mean_calculation.c -o mean_calculation
Run the program:
./mean_calculation
Example output:
Enter the number of elements (max 100): 4
Enter 4 numbers:
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40
Entered numbers are:
10 20 30 40
Statistics:
Number of elements: 4
Sum of numbers: 100
Mean of numbers: 25.00
Key improvements in this version:
- Created a separate
calculateMean()
function
- Added more detailed statistical output
- Improved error handling for edge cases
- Maintained the same core functionality as previous steps
- Made the code more modular and easier to read
The program demonstrates:
- Function-based approach to calculations
- Comprehensive statistical output
- Modular code design