CSharp - Write program to Use Conditional Operator to check value

Requirements

You will flip a coin and get the "Head and Tail" using the conditional operator.

Hint

if-else construction can be replaced with the conditional operator.

The conditional operator ?: syntax looks like this:

condition ? yesValue : noValue 

It returns:

  • yesValue if the condition holds (is fulfilled)
  • noValue otherwise

The condition is an equality test of the randomNumber variable against zero.

If it is true, the message variable is assigned the "Head tossed" text.

Otherwise, it is assigned the "Tail tossed" text.

The conditional operator is also called a ternary operator since it is the only operator that accepts three operands: a condition, a yesValue, and a noValue.

Demo

using System;
class Program// ww w  . jav  a  2  s.com
{
    static void Main(string[] args)
    {
        // Random number generator 
        Random randomNumbers = new Random();

        // Random number 0/1 and its transformation 
        int randomNumber = randomNumbers.Next(0, 1 + 1);
        string message = randomNumber == 0 ? "Head tossed" : "Tail tossed";
        Console.WriteLine(message);

    }
}

Result