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

Here, we are going to learn about the use of a ternary conditional operator and its C# implementation.
Submitted by Nidhi, on September 10, 2020

Here we will use the ?: ternary operator, it is also known as a conditional operator. We can check conditions use this operator. Most of the "if" statement can be replaced by the ?: conditional operator.

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 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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.