Home » C# » C# programs » C# basic programs

C# program to demonstrate example of nested conditional operator

C# nested conditional operator example: Here, we are writing a C# program to demonstrate example of nested conditional operator.
Submitted by IncludeHelp, on April 07, 2019

C# (or other programming languages also) allows to use a conditional/ternary operator within another conditional/ternary operator.

Syntax:

    (logical_test1) ? 
        ((logical_test2)? True_block : false_block) : 
        false_block_outer;

If logical_test1 is true then logical_test2 will be checked, if it is true then "true_block" executes, else "false_block" executes, and if logical_test1 is false then "false_block_outer" will be executed.

Note: Inner conditional operator can be used in any block as per the requirement.

C# example for nested conditional/ternary operator

Here, we are asking to input three numbers and finding the largest number.

// C# program to demonstrate example of 
// nested conditional operator
using System;
using System.IO;
using System.Text;

namespace IncludeHelp
{
    class Test
    {
        // Main Method 
        static void Main(string[] args)
        {
            //finding largest of three  numbers 
            int a;
            int b;
            int c;

            //input numbers 
            Console.Write("Enter first number : ");
            a = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter second number: ");
            b = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter third number : ");
            c = Convert.ToInt32(Console.ReadLine());

            //finding largest number
            int large = (a>b)?((a>c)?a:c):(b>c?b:c);

            Console.WriteLine("Largest number is {0}", large);

            //hit ENTER to exit the program
            Console.ReadLine();
        }
    }
}

Output

First run:
Enter first number : 30
Enter second number: 20
Enter third number : 10
Largest number is 30

Second run:
Enter first number : 10
Enter second number: 30
Enter third number : 20
Largest number is 30

Third run:
Enter first number : 10
Enter second number: 20
Enter third number : 30
Largest number is 30






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







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.