Thursday 9 June 2016

Greatest of 3 numbers

If 1st number is greater than the 2nd number,then compare 1st number with 3rd number.Whichever is greater,is greatest of 3 numbers.
If 2nd number is greater than 1st number,compare 2nd number with 3rd number.Whichever is greater,is greatest of 3 numbers.


Code

#include<stdio.h>

int main()
{
    int n1,n2,n3;

    printf("\nEnter 3 numbers ");
    scanf("%d %d %d",&n1,&n2,&n3);

    if(n1 > n2)
    { 
        if(n1 > n3)
            printf("Greatest number = %d",n1);
        else
            printf("Greatest number = %d",n3);
    }
    else
    {
        if(n2 > n3)
            printf("Greatest number = %d",n2);
        else
            printf("Greatest number = %d",n3);
    }       

    return 0;
}

O/P



This can also be done using a ternary operator.
max = (n1-n2) > 0?(n1-n3) > 0?n1:n3:(n2-n3) > 0?n2:n3;

No comments:

Post a Comment