Q:

C# program to demonstrate the use of a ternary conditional operator

0

C# program to demonstrate the use of a ternary conditional operator

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

//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 num1num2, 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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< Using string with switch case statement in C#...