Pages - Menu

Friday 12 October 2012

Maximum and minimum of three numbers using the ternary operator

Maximum


The following function finds and returns the largest of the three numbers received as arguments in the function call using the ternary operator.
/*
 * Description:
 *  Finds the largest of three numbers using nested if statements
 * Parameters:
 *  a - the first number out of the three
 *  b - the second number out of the three
 *  c - the third number out of the three
 * Returns:
 *  maximum - the largest number out of the three
 */
int Maximum(int a, int b, int c)
{
    int maximum = (((a > b) && (a > c)) ? a : (b > c) ? b : c);
    return maximum;
}

Minimum


The following function finds and returns the smallest of the three numbers received as arguments in the function call using the ternary operator.
/*
 * Description:
 *  Finds the smallest of three numbers using nested if statements
 * Parameters:
 *  a - the first number out of the three
 *  b - the second number out of the three
 *  c - the third number out of the three
 * Returns:
 *  minimum - the smallest number out of the three
 */
int Minimum(int a, int b, int c)
{
    int minimum = (((a < b) && (a < c)) ? a : (b < c) ? b : c);
    return minimum;
}

Example:

#include<stdio.h>
#include<conio.h>

int Maximum(int a, int b, int c);
int Minimum(int a, int b, int c);

int main(void)
{
    int a = 0, b = 0, c = 0;
    int maximum = 0, minimum = 0;
    printf("\n Enter the first number: ");
    scanf("%d",&a);
    printf(" Enter the second number: ");
    scanf("%d",&b);
    printf(" Enter the third number: ");
    scanf("%d",&c);
    maximum = Maximum(a,b,c);
    printf("\n\t\t\tThe largest number is: %d",maximum);
    minimum = Minimum(a,b,c);
    printf("\n\t\t\tThe smallest number is: %d",minimum);
    getch();
    return 0;
} 
Output: 

For more ways to find the maximum and minimum of three numbers, see these two articles: one, two.

No comments:

Post a Comment