How to find the median among three given numbers in C

1 Answer

0 votes
#include <stdio.h>

// Function to compute the median of three integers
int median_of_three_numbers(int a, int b, int c) {
    // Find the minimum of the three numbers
    int min = a;
    if (b < min) min = b;
    if (c < min) min = c;

    // Find the maximum of the three numbers
    int max = a;
    if (b > max) max = b;
    if (c > max) max = c;

    // Median = sum of all three minus min and max
    return a + b + c - min - max;
}

int main() {
    // Test cases similar to your C++ example
    printf("The median of [1, 1, 1] is %d\n",
           median_of_three_numbers(1, 1, 1));

    printf("The median of [10, 3, 7] is %d\n",
           median_of_three_numbers(10, 3, 7));

    printf("The median of [10, -10, -10] is %d\n",
           median_of_three_numbers(10, -10, -10));

    printf("The median of [3, 3, 5] is %d\n",
           median_of_three_numbers(3, 3, 5));

    return 0;
}


/*
run:

The median of [1, 1, 1] is 1
The median of [10, 3, 7] is 7
The median of [10, -10, -10] is -10
The median of [3, 3, 5] is 3

*/

 



answered Mar 26 by avibootz
...