C# Program - Find Largest Number among three Numbers


Advertisements

Three numbers $$x$$, $$y$$ and $$z$$ are given and the largest number among these three numbers can be found out using below methods.

Example: Using If statement

In the below example, only if conditional statements are used.

using System;

namespace MyApplication { 
  class MyProgram {
    static void largest(int x, int y, int z) {
      int max = x;
      if (x >= y && x >= z)
        {max = x;}
      if (y >= x && y >= z)
        {max = y;}
      if (z >= x && z >= y)
        {max = z;}
      Console.WriteLine("largest number among " + x + ", " + y + " and " + z + " is: " + max);
    }  

    static void Main(string[] args) {
      largest(100, 50, 25);
      largest(50, 50, 25);
    }
  }
}

Output

largest number among 100 , 50 and 25 is:  100
largest number among 50 , 50 and 25 is:  50

Example: Using If-else statement

It can also be solved using If-else conditional statements.

using System;

namespace MyApplication { 
  class MyProgram {
    static void largest(int x, int y, int z) {
      int max = x;
      if (x >= y && x >= z)
        {max = x;}
      else if (y >= x && y >= z)
        {max = y;}
      else 
        {max = z;}
      Console.WriteLine("largest number among " + x + ", " + y + " and " + z + " is: " + max);
    }  

    static void Main(string[] args) {
      largest(100, 50, 25);
      largest(50, 50, 25);
    }
  }
}

Output

largest number among 100 , 50 and 25 is:  100
largest number among 50 , 50 and 25 is:  50

Example: Using Nested If-else statement

The above problem can also be solved using nested if-else conditional statements.

using System;

namespace MyApplication { 
  class MyProgram {
    static void largest(int x, int y, int z) {
      int max = x;
      if (x >= y)
        {
          if(x >= z) 
            {max = x;}
          else
            {max = z;}
        }
      else
        {
          if(y >= z) 
            {max = y;}
          else
            {max = z;}
        }
      Console.WriteLine("largest number among " + x + ", " + y + " and " + z + " is: " + max);
    }  

    static void Main(string[] args) {
      largest(100, 50, 25);
      largest(50, 50, 25);
    }
  }
}

Output

largest number among 100 , 50 and 25 is:  100
largest number among 50 , 50 and 25 is:  50

Example: Using ternary operator

The ternary operator can also be used here.

using System;

namespace MyApplication { 
  class MyProgram {
    static void largest(int x, int y, int z) {
      int max = x;
      max = (x > y)? ((x > z)? x : z) : ((y > z)? y : z);
      Console.WriteLine("largest number among " + x + ", " + y + " and " + z + " is: " + max);
    }  

    static void Main(string[] args) {
      largest(100, 50, 25);
      largest(50, 50, 25);
    }
  }
}

Output

largest number among 100 , 50 and 25 is:  100
largest number among 50 , 50 and 25 is:  50



Recommended Pages


Advertisements