Program to Find the Greatest of Two Numbers in C
Finding the Greatest of Two Numbers
Given two integer inputs num1 and num2, the objective is to determine which number is greater using C programming.
We will explore different methods to achieve this.
Method 1: Using if-else Statement
We use an if-else statement to compare two numbers and determine the greatest one.
#include <stdio.h>
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
if (num1 > num2) {
printf("%d is the greatest number", num1);
} else if (num2 > num1) {
printf("%d is the greatest number", num2);
} else {
printf("Both numbers are equal");
}
return 0;
}
Output:
Enter two numbers: 5 10 10 is the greatest number
Method 2: Using Ternary Operator
We use the ternary operator ?: to find the greatest number in a single line.
#include <stdio.h>
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
int greatest = (num1 > num2) ? num1 : num2;
printf("%d is the greatest number", greatest);
return 0;
}
Output:
Enter two numbers: 7 3 7 is the greatest number
Method 3: Using Function
We create a function to compare two numbers and return the greatest one.
#include <stdio.h>
int findGreatest(int a, int b) {
return (a > b) ? a : b;
}
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("%d is the greatest number", findGreatest(num1, num2));
return 0;
}
Output:
Enter two numbers: 4 9 9 is the greatest number