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 num1 with num2

  • If num1 is greater, compare num1 with num3

  • If num2 is greater than num1, compare num2 with num3

  • The winner of each comparison is the maximum

Finding Maximum Logic Flow num1 num2 num3 vs vs Maximum Compare pairs to find the largest number

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.

Updated on: 2026-03-17T07:04:35+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements