Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to find the maximum of three numbers
Finding the maximum of three numbers is a fundamental programming problem that demonstrates conditional logic and comparison operations. This can be achieved using nested if-else statements to compare the numbers systematically.
Logic
The algorithm compares numbers in pairs −
First, compare
num1withnum2If
num1is greater, comparenum1withnum3If
num2is greater thannum1, comparenum2withnum3The winner of each comparison is the maximum
Using Nested If-Else Statements
Example
using System;
class Program {
static void Main() {
int num1, num2, num3;
// Set the value of the three numbers
num1 = 10;
num2 = 20;
num3 = 50;
Console.WriteLine($"Numbers: {num1}, {num2}, {num3}");
if (num1 > num2) {
if (num1 > num3) {
Console.WriteLine($"Maximum number is: {num1}");
} else {
Console.WriteLine($"Maximum number is: {num3}");
}
} else if (num2 > num3) {
Console.WriteLine($"Maximum number is: {num2}");
} else {
Console.WriteLine($"Maximum number is: {num3}");
}
}
}
The output of the above code is −
Numbers: 10, 20, 50 Maximum number is: 50
Using Math.Max() Method
Example
using System;
class Program {
static void Main() {
int num1 = 45;
int num2 = 78;
int num3 = 23;
Console.WriteLine($"Numbers: {num1}, {num2}, {num3}");
int maximum = Math.Max(Math.Max(num1, num2), num3);
Console.WriteLine($"Maximum number is: {maximum}");
}
}
The output of the above code is −
Numbers: 45, 78, 23 Maximum number is: 78
Using Ternary Operator
Example
using System;
class Program {
static void Main() {
int num1 = 100;
int num2 = 85;
int num3 = 92;
Console.WriteLine($"Numbers: {num1}, {num2}, {num3}");
int maximum = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);
Console.WriteLine($"Maximum number is: {maximum}");
}
}
The output of the above code is −
Numbers: 100, 85, 92 Maximum number is: 100
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Nested If-Else | High | Good | Learning and clear logic flow |
| Math.Max() | High | Excellent | Clean, built-in solution |
| Ternary Operator | Medium | Good | Compact one-liner solutions |
Conclusion
Finding the maximum of three numbers can be accomplished using nested if-else statements, Math.Max() method, or ternary operators. The Math.Max() approach is generally preferred for its simplicity and readability, while nested if-else provides the clearest logic flow for beginners.
