C# Program to Find Largest of Three Numbers
if-else statements like this: if (a >= b && a >= c) largest = a; else if (b >= a && b >= c) largest = b; else largest = c;.Examples
How to Think About It
&& to check if it is greater or equal to both. If true, it is the largest. Otherwise, check the second number similarly. If neither the first nor second is largest, the third must be the largest.Algorithm
Code
using System; class Program { static void Main() { int a = 3, b = 7, c = 5; int largest; if (a >= b && a >= c) { largest = a; } else if (b >= a && b >= c) { largest = b; } else { largest = c; } Console.WriteLine(largest); } }
Dry Run
Let's trace the example where a=3, b=7, c=5 through the code.
Compare a with b and c
Check if 3 >= 7 and 3 >= 5 (false)
Compare b with a and c
Check if 7 >= 3 and 7 >= 5 (true)
Assign largest
largest = 7
Print largest
Output: 7
| Step | Condition | Result | Largest |
|---|---|---|---|
| 1 | 3 >= 7 && 3 >= 5 | false | N/A |
| 2 | 7 >= 3 && 7 >= 5 | true | 7 |
| 3 | Assign largest | - | 7 |
| 4 | Print largest | - | 7 |
Why This Works
Step 1: Compare first number
We use if (a >= b && a >= c) to check if the first number is greater or equal to both others.
Step 2: Compare second number
If the first is not largest, check if the second number is greater or equal to both others with else if (b >= a && b >= c).
Step 3: Assign third number
If neither first nor second is largest, the third number must be largest, so assign it.
Step 4: Print result
Finally, print the largest number to show the result.
Alternative Approaches
using System; class Program { static void Main() { int a = 3, b = 7, c = 5; int largest = Math.Max(a, Math.Max(b, c)); Console.WriteLine(largest); } }
using System; class Program { static void Main() { int a = 3, b = 7, c = 5; int largest = (a >= b && a >= c) ? a : (b >= c ? b : c); Console.WriteLine(largest); } }
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of comparisons regardless of input size, so it runs in constant time O(1).
Space Complexity
Only a few variables are used to store inputs and the largest number, so space complexity is O(1).
Which Approach is Fastest?
All approaches run in constant time; using Math.Max is concise but function calls may have slight overhead compared to direct comparisons.
| Approach | Time | Space | Best For |
|---|---|---|---|
| If-else comparisons | O(1) | O(1) | Clear logic for beginners |
| Math.Max function | O(1) | O(1) | Concise and clean code |
| Ternary operator | O(1) | O(1) | Compact code, less readable for beginners |
Math.Max for a quick and clean way to find the largest number.&& to compare the first number with both others, causing wrong results.