When working with numbers in programming, comparing two values is a fundamental task. In this article, we will explain how to compare two numbers in C# and determine which one is greater using a simple program.
Code Example
Below is a sample C# code that compares two numbers input by the user and displays the greater number:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | int number1, number2; Console.Write("Enter the First Number : "); number1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the Second Number : "); number2 = Convert.ToInt32(Console.ReadLine()); if (number1 > number2) { Console.WriteLine("{0} is the Greater number then {1}", number1, number2); } else { Console.WriteLine("{0} is the Greater number then {1}", number2, number1); } Console.ReadLine(); |
Explanation of the Code
- User Input:
- The program first prompts the user to enter two numbers.
Console.ReadLine()
is used to read input from the user as a string.- The
Convert.ToInt32()
method converts the input string into an integer.
- Comparison Logic:
- An
if-else
statement is used to compare the two numbers. - If
number1
is greater thannumber2
, the program outputs thatnumber1
is the greater number. - Otherwise, it assumes
number2
is greater and outputs the corresponding message.
- An
- Output:
- The
Console.WriteLine()
method is used to display the result to the user. - The placeholders
{0}
and{1}
in the string are replaced with the values ofnumber1
andnumber2
respectively.
- The
- Program End:
Console.ReadLine()
at the end prevents the program from closing immediately, allowing the user to see the result.
Sample Input and Output
Input:
1 2 3 4 | Enter the First Number: 15 Enter the Second Number: 8 |
Output: