Q:

Write a C program to find Largest Number among three numbers

0

C program to find Largest Number among three numbers

This program will take three integer numbers from user and find largest number among them; we will find largest number using two methods - if else and conditional operators.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program for Largest Number among three numbers

/* c program to find largest number among 3 numbers*/
#include <stdio.h>
 
int main()
{ 
    int a,b,c;
    int largest;
 
    printf("Enter three numbers (separated by space):");
    scanf("%d%d%d",&a,&b,&c);
 
    if(a>b && a>c)        
        largest=a;
    else if(b>a && b>c)       
        largest=b;
    else
        largest=c;
 
    printf("Largest number is = %d",largest);
 
    return 0;
}

Using Ternary Operator (? : Operator)

Instead of using if else we can also get the largest number among three number by using Ternary Operator (? :) Operator in C.

Consider the code snippet

    largest = ((a>b && a>c)? a : ((b>a && b>c)? b : c));

Consider the example,

/*using ternary operator (? :) */
#include <stdio.h>
 
int main()
{ 
    int a,b,c;
    int largest;
 
    printf("Enter three numbers (separated by space):");
    scanf("%d%d%d",&a,&b,&c);
 
    largest =((a>b && a>c)?a:((b>a && b>c)?b:c));
 
    printf("Largest number is = %d",largest);
 
    printf("Largest number is = %d",largest);   
    return 0;
}

Output

First Run:
Enter three numbers (separated by space): 10 20 30
Largest number is = 30

Second Run:
Enter three numbers (separated by space):10 30 20
Largest number is = 30

Third Run:
Enter three numbers (separated by space):30 10 20
Largest number is = 30

Fourth Run:
Enter three numbers (separated by space):30 30 30
Largest number is = 30

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now