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
How to find maximum between 2 numbers using C#?
Finding the maximum between two numbers in C# can be accomplished using several approaches. The most common methods include using conditional statements, the Math.Max() method, and the ternary operator.
Using If-Else Statement
The traditional approach uses an if-else statement to compare two numbers and determine which one is larger −
using System;
class Program {
static void Main(string[] args) {
int num1 = 50;
int num2 = 90;
int maxNum;
Console.WriteLine("Number 1: " + num1);
Console.WriteLine("Number 2: " + num2);
if (num1 > num2) {
maxNum = num1;
} else {
maxNum = num2;
}
Console.WriteLine("Maximum number is: " + maxNum);
}
}
The output of the above code is −
Number 1: 50 Number 2: 90 Maximum number is: 90
Using Math.Max() Method
The Math.Max() method provides a cleaner and more concise way to find the maximum of two numbers −
using System;
class Program {
static void Main(string[] args) {
int num1 = 75;
int num2 = 45;
Console.WriteLine("Number 1: " + num1);
Console.WriteLine("Number 2: " + num2);
int maxNum = Math.Max(num1, num2);
Console.WriteLine("Maximum number is: " + maxNum);
// Works with different data types
double d1 = 12.5, d2 = 18.3;
double maxDouble = Math.Max(d1, d2);
Console.WriteLine("Maximum of " + d1 + " and " + d2 + " is: " + maxDouble);
}
}
The output of the above code is −
Number 1: 75 Number 2: 45 Maximum number is: 75 Maximum of 12.5 and 18.3 is: 18.3
Using Ternary Operator
The ternary operator ?: provides a concise one-line solution for finding the maximum −
using System;
class Program {
static void Main(string[] args) {
int num1 = 100;
int num2 = 85;
Console.WriteLine("Number 1: " + num1);
Console.WriteLine("Number 2: " + num2);
int maxNum = (num1 > num2) ? num1 : num2;
Console.WriteLine("Maximum number is: " + maxNum);
}
}
The output of the above code is −
Number 1: 100 Number 2: 85 Maximum number is: 100
Comparison of Methods
| Method | Advantages | Best For |
|---|---|---|
| If-Else | Clear logic flow, easy to understand | Beginners, complex conditions |
| Math.Max() | Built-in method, works with multiple data types | Professional code, multiple data types |
| Ternary Operator | Concise, one-line solution | Simple comparisons, compact code |
Conclusion
Finding the maximum between two numbers in C# can be done using if-else statements, the Math.Max() method, or the ternary operator. The Math.Max() method is generally preferred for its simplicity and built-in reliability, while if-else statements provide clarity for complex logic.
