Home » C programs » C basic programs

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.

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.