C program to find the largest or greatest of two numbers; Through this tutorial, we will learn how to find the largest of two numbers in the c program using if statement, condition operator, switch case, and ternary operator.
Programs and Algorithm to Find Largest of Two Numbers in C
- Algorithm to Find Largest of Two Numbers
- C Program to Find Largest of Two Numbers using Else If Statement
- C Program to Find Largest of Two Numbers using Conditional Operator
- C Program to Find Largest of Two Numbers using Switch Case
- C Program to Find Largest of Two Numbers using Ternary Operator
Algorithm to Find Largest of Two Numbers
Use the following algorithm to write a c program to find largest of two number; as follows:
- Start program
- Read the two integer values in program.
- Check if num1 is greater than num2.
- If true, then print ‘num1’ as the greatest number.
- If false, then print ‘num2’ as the greatest number.
- End program
C Program to Find Largest of Two Numbers using Else If Statement
/* C Program to Find Largest of Two numbers */ #include <stdio.h> int main() { int a, b; printf("Please Enter Two different values :- "); scanf("%d %d", &a, &b); if(a > b) { printf("%d is Largest\n", a); } else if (b > a) { printf("%d is Largest\n", b); } else { printf("Both are Equal\n"); } return 0; }
The output of the above c program; as follows:
Please Enter Two different values :- 10 25 25 is Largest
C Program to Find Largest of Two Numbers using Conditional Operator
/* C Program to Find Largest of Two numbers */ #include <stdio.h> int main() { int a, b, largest; printf("Please Enter Two Different Values :- "); scanf("%d %d", &a, &b); if(a == b) { printf("Both are Equal\n"); } else { largest = (a > b) ? a : b; printf("%d is Largest\n", largest); } return 0; }
The output of the above c program; as follows:
Please Enter Two Different Values :- 100 2 100 is Largest
C Program to Find Largest of Two Numbers using Switch Case
/* C Program to Find Largest of Two numbers */ #include <stdio.h> int main() { int a, b, largest; printf("Please Enter Two Values :- "); scanf("%d %d", &a, &b); switch(a > b) { case 1: printf("%d is Largest", a); break; case 2: printf("%d is Largest", b); break; } return 0; }
The output of the above c program; as follows:
Please Enter Two Values :- 63 36 63 is Largest
C Program to Find Largest of Two Numbers using Ternary Operator
#include <stdio.h> int main() { int num1, num2; // Ask user to enter the two numbers printf("Please Enter Two different values :- "); // Read two numbers from the user scanf("%d %d", &num1, &num2); (num1 >= num2)?((num1 ==num2)?printf("Both numbers are equal"):printf("%d is Largest\n", num1)):printf("%d is Largest\n", num2); return 0; }
The output of the above c program; as follows:
Please Enter Two different values :- 40 30 40 is Largest