if-else
.#include <stdio.h>
int main() {
int num1, num2;
// Input two numbers
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Find the greatest number
if (num1 > num2) {
printf("The greatest number is: %d\n", num1);
} else if (num2 > num1) {
printf("The greatest number is: %d\n", num2);
} else {
printf("Both numbers are equal.\n");
}
return 0;
}
if-else
statement to compare the numbers.#include <stdio.h>
int main() {
int num1, num2, num3;
// Input three numbers
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
// Find the greatest number using if-else
if (num1 >= num2 && num1 >= num3) {
printf("The greatest number is: %d\n", num1);
} else if (num2 >= num1 && num2 >= num3) {
printf("The greatest number is: %d\n", num2);
} else {
printf("The greatest number is: %d\n", num3);
}
return 0;
}
&&
) to check which number is the largest.Instead of using if-else
, the ternary operator (? :
) can be used for concise code.
#include <stdio.h>
int main() {
int num1, num2;
// Input two numbers
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Find the greatest number using ternary operator
int greatest = (num1 > num2) ? num1 : num2;
printf("The greatest number is: %d\n", greatest);
return 0;
}
#include <stdio.h>
int main() {
int num1, num2, num3;
// Input three numbers
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
// Find the greatest number using nested ternary operator
int greatest = (num1 > num2) ? ((num1 > num3) ? num1 : num3)
: ((num2 > num3) ? num2 : num3);
printf("The greatest number is: %d\n", greatest);
return 0;
}
Input | Expected Output |
---|---|
10 20 | The greatest number is: 20 |
-5 -10 | The greatest number is: -5 |
30 30 | Both numbers are equal. |
10 15 7 | The greatest number is: 15 |
50 25 75 | The greatest number is: 75 |
-2 -5 -10 | The greatest number is: -2 |
Approach | Time Complexity | Space Complexity |
---|---|---|
If-else approach | O(1) | O(1) |
Ternary operator approach | O(1) | O(1) |
Both approaches run in constant time O(1) since only a few comparisons are made.
These programs are frequently asked in placement interviews and are useful for building logic in competitive programming.