In this final step, you will enhance the median calculation program to provide more detailed output and demonstrate different ways of presenting the median.
Open the existing file to make final modifications:
cd ~/project
nano median_calculator.c
Update the code with improved output formatting:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Previous functions (readArray, sortArray, printArray, calculateMedian) remain the same
void printDetailedMedianInfo(int arr[], int n, float median) {
printf("\n--- Median Calculation Details ---\n");
printf("Total number of elements: %d\n", n);
printf("Array elements: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n\nMedian Calculation:\n");
if (n % 2 != 0) {
printf("Odd number of elements\n");
printf("Middle index: %d\n", n / 2);
printf("Middle element: %d\n", arr[n / 2]);
} else {
printf("Even number of elements\n");
printf("Two middle indices: %d and %d\n", (n / 2) - 1, n / 2);
printf("Middle elements: %d and %d\n", arr[(n / 2) - 1], arr[n / 2]);
}
printf("\nFinal Median: %.2f\n", median);
}
int main() {
int arr[MAX_SIZE];
int n;
readArray(arr, &n);
sortArray(arr, n);
float median = calculateMedian(arr, n);
// Print sorted array
printArray(arr, n);
// Print detailed median information
printDetailedMedianInfo(arr, n, median);
return 0;
}
Compile and run the updated program:
gcc median_calculator.c -o median_calculator
./median_calculator
Example output for odd number of elements:
Enter the number of elements (max 100): 5
Enter 5 elements:
42
15
7
23
11
Sorted array: 7 11 15 23 42
--- Median Calculation Details ---
Total number of elements: 5
Array elements: 7 11 15 23 42
Median Calculation:
Odd number of elements
Middle index: 2
Middle element: 15
Final Median: 15.00
Example output for even number of elements:
Enter the number of elements (max 100): 6
Enter 6 elements:
42
15
7
23
11
8
Sorted array: 7 8 11 15 23 42
--- Median Calculation Details ---
Total number of elements: 6
Array elements: 7 8 11 15 23 42
Median Calculation:
Even number of elements
Two middle indices: 2 and 3
Middle elements: 11 and 15
Final Median: 13.00
Key improvements in this step:
- Added a new function
printDetailedMedianInfo()
- Provides comprehensive information about median calculation
- Shows different scenarios for odd and even number of elements
- Enhances user understanding of median computation