C Program to Find Largest of Three Numbers
if (a > b && a > c) largest = a; and print the largest value.Examples
How to Think About It
&& to check if it is greater than both. If true, it is the largest. Otherwise, compare the second number with the third. The one that passes the comparison is the largest.Algorithm
Code
#include <stdio.h> int main() { int a, b, c, largest; printf("Enter three numbers: "); scanf("%d %d %d", &a, &b, &c); if (a >= b && a >= c) { largest = a; } else if (b >= c) { largest = b; } else { largest = c; } printf("Largest number is %d\n", largest); return 0; }
Dry Run
Let's trace the input a=5, b=3, c=9 through the code
Input values
a=5, b=3, c=9
Check if a >= b and a >= c
5 >= 3 is true, 5 >= 9 is false, so condition is false
Check if b >= c
3 >= 9 is false
Set largest to c
largest = 9
Print largest
Output: Largest number is 9
| Step | Condition | Result | Largest |
|---|---|---|---|
| 1 | a >= b && a >= c | false | |
| 2 | b >= c | false | |
| 3 | Set largest = c | 9 |
Why This Works
Step 1: Compare first number
The code uses if (a >= b && a >= c) to check if the first number is greater than or equal to both others.
Step 2: Compare second number
If the first number is not largest, it checks if the second number is greater than or equal to the third using else if (b >= c).
Step 3: Assign largest
If neither first nor second is largest, the third number is assigned as largest by default.
Alternative Approaches
#include <stdio.h> int main() { int a, b, c, largest; printf("Enter three numbers: "); scanf("%d %d %d", &a, &b, &c); if (a >= b) { if (a >= c) { largest = a; } else { largest = c; } } else { if (b >= c) { largest = b; } else { largest = c; } } printf("Largest number is %d\n", largest); return 0; }
#include <stdio.h> int main() { int a, b, c, largest; printf("Enter three numbers: "); scanf("%d %d %d", &a, &b, &c); largest = (a >= b) ? ((a >= c) ? a : c) : ((b >= c) ? b : c); printf("Largest number is %d\n", largest); return 0; }
Complexity: O(1) time, O(1) space
Time Complexity
The program uses a fixed number of comparisons (at most two), so it runs in constant time regardless of input.
Space Complexity
Only a few variables are used to store input and the largest number, so space usage is constant.
Which Approach is Fastest?
All approaches run in constant time; ternary operator is concise but nested if-else may be clearer for beginners.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple if-else | O(1) | O(1) | Beginners, clarity |
| Nested if-else | O(1) | O(1) | Slightly fewer comparisons in some cases |
| Ternary operator | O(1) | O(1) | Compact code, experienced programmers |
&& when comparing the first number with both others.