Write A C# Program To Find The Largest Of Three Numbers

Do you want to find out the largest of three numbers in C#. In this C# tutorial, I will explain how to write a C# program to find the largest of three numbers.

To find the largest of three numbers in C#, you can use a simple if-else statement to compare the numbers. Start by reading the user input for three numbers, then compare them using nested if-else statements. The program identifies the largest number by checking each number against the others, ultimately displaying the largest one to the user.

Find The Largest Of Three Numbers in C#

To find the largest of the three numbers, we need to compare them with each other. This can be done using if-else statements in C#. We will compare the first number with the second and third, and then, if necessary, compare the second with the third.

Here is the complete C# program to find the largest of three numbers.

using System;

class LargestOfThree
{
    static void Main()
    {
        int num1, num2, num3, largest;

        // User inputs for the three numbers
        Console.WriteLine("Enter the first number:");
        num1 = Convert.ToInt32(Console.ReadLine());
        
        Console.WriteLine("Enter the second number:");
        num2 = Convert.ToInt32(Console.ReadLine());
        
        Console.WriteLine("Enter the third number:");
        num3 = Convert.ToInt32(Console.ReadLine());

        // Comparing numbers to find the largest
        if (num1 >= num2 && num1 >= num3)
        {
            largest = num1;
        }
        else if (num2 >= num1 && num2 >= num3)
        {
            largest = num2;
        }
        else
        {
            largest = num3;
        }

        // Displaying the result
        Console.WriteLine("The largest number is: " + largest);
    }
}

Here is the complete code explanation:

  • Namespace and Class Declaration: We start by using the System namespace and declaring a class LargestOfThree.
  • Main Method: The Main method is the entry point of a C# application.
  • Declaring Variables: We declare four integer variables: num1, num2, num3, and largest.
  • User Input: We prompt the user to enter three numbers, reading and converting their input to integers.
  • Comparison Logic: Using if-else statements, we compare the numbers to find the largest.
  • Displaying the Result: Finally, we print the largest number to the console.

Once you execute the code, it will ask you three numbers to input and display the largest of the three numbers.

Here is the screenshot:

Write A C# Program To Find The Largest Of Three Numbers

Conclusion

This C# program provides a straightforward solution to determine the largest of three numbers. It’s an excellent example of applying basic programming constructs like variables, user input, conditional statements, and console output in C#. I hope you enjoyed the article “write a c# program to find the largest of three numbers.”

You may also like: