Syntax using if-else:
if (a > b)
large = a;
else
large = b;
Syntax using the ternary operator:
large = (a > b) ? a : b;
C# code to find the largest of two numbers:
span style='color:#696969; '>// C# program to find largest of two numbers
using System;
using System.IO;
using System.Text;
namespace JustTechReview
{
class Test
{
// Main Method
static void Main(string[] args)
{
int a;
int b;
int large;
//input the numbers
Console.Write("Enter first number : ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second number: ");
b = Convert.ToInt32(Console.ReadLine());
//finding largest number using if-else
if (a > b)
large = a;
else
large = b;
//printing
Console.WriteLine("Using if-else...");
Console.WriteLine("Largest number is {0}", large);
//finding largest number using ternary operator
large = (a > b) ? a : b;
//printing
Console.WriteLine("Using if-else...");
Console.WriteLine("Largest number is {0}", large);
//hit ENTER to exit the program
Console.ReadLine();
}
}
}
Output:
First run:
Enter first number : 10
Enter second number: 20
Using if-else...
Largest number is 20
Using if-else...
Largest number is 20
Second run:
Enter first number : 20
Enter second number: 10
Using if-else...
Largest number is 20
Using if-else...
Largest number is 20
Third run:
Enter first number : 20
Enter second number: 20
Using if-else...
Largest number is 20
Using if-else...
Largest number is 20