×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous 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.

Largest Number among three numbers using nested if else

/* 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;
}

Largest Number among three numbers using ternary operator

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

Code snippet

Consider the code snippet
largest = ((a>b && a>c)? a : ((b>a && b>c)? b : c));

C program to find Largest Number among three numbers using ternary operator

/*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

C Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.