The source code to demonstrate the use of a ternary conditional operator is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# Program to demonstrate the use of the
//conditional ternary operator
using System;
class Sample
{
static void Main()
{
int num1 = 0;
int num2 = 0;
int large = 0;
Console.Write("Enter num1: "); num1 = int.Parse(Console.ReadLine());
Console.Write("Enter num2: "); num2 = int.Parse(Console.ReadLine());
large = (num1 > num2) ? num1 : num2;
Console.WriteLine("Large: " + large);
}
}
Output:
Enter num1: 5
Enter num2: 6
Large: 6
Press any key to continue . . .
Explanation:
In the above program, we created a Sample class that contains the Main() method. In the Main() method we declared three local variables num1, num2, and large initialized with 0. Then we read the values of num1 and num2.
large = (num1 > num2) ? num1 : num2;
Using the above statement, we find the largest number from num1 and num2 and assigned to the variable large. Here if condition (num1>num2) is true then the value of num1 is assigned to the variable large otherwise the value of num2 will be assigned in the variable large. Then finally we printed the value of the variable large on the console screen.
Program:
The source code to demonstrate the use of a ternary conditional operator is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a Sample class that contains the Main() method. In the Main() method we declared three local variables num1, num2, and large initialized with 0. Then we read the values of num1 and num2.
Using the above statement, we find the largest number from num1 and num2 and assigned to the variable large. Here if condition (num1>num2) is true then the value of num1 is assigned to the variable large otherwise the value of num2 will be assigned in the variable large. Then finally we printed the value of the variable large on the console screen.