Home Programs How to find the largest of three numbers in C#

How to find the largest of three numbers in C#

In this example we show how to find the largest of three user inputted integers

We will use an if – else statement

Example

 

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int myNumber1;
            int myNumber2;
            int myNumber3;
            int largestNumber;

            //input the numbers
            Console.Write("Enter first number : ");
            myNumber1 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter second number: ");
            myNumber2 = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter third number : ");
            myNumber3 = Convert.ToInt32(Console.ReadLine());

            //finding largest number using if-else
            if (myNumber1 > myNumber2 && myNumber1 > myNumber3)
                largestNumber = myNumber1;
            else if (myNumber2 > myNumber1 && myNumber2 > myNumber3)
                largestNumber = myNumber2;
            else largestNumber = myNumber3;

            //print largest number
            Console.WriteLine("Largest number is {0}", largestNumber);

            Console.ReadLine();
        }
    }
}

Here is a test run

Enter first number : 5
Enter second number: 6
Enter third number : 4
Largest number is 6

You may also like