Monday, January 2, 2012

2.1.8. Conditional operator: ?

In C#, there is another way to assign a value if a condition is true or not. It is the "conditional operator"? :

   variableName = condition ?  value1 : value2;

which means "if the condition is met, variableName is set to value1, otherwise it is set to value2".

This is an example of how we might use it to calculate the greatest of two numbers:

   greatestValue = a>b ?  a : b;

which is equivalent to the following "if" statement:



    if ( a > b )
        greatestValue = a;
    else
        greatestValue = b;

And could be used in a simple program like this one:

/*---------------------------*/
/*  C# Example #12:          */
/*  example12.cs             */
/*                           */
/*  The conditional operator */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example12
{
  public static void Main()
  {
    int a, b, greatestValue;

    Console.Write("Enter a number: ");
    a = Convert.ToInt32(Console.ReadLine());
    Console.Write("Enter another: ");
    b = Convert.ToInt32(Console.ReadLine());

    greatestValue = (a>b) ?  a : b;
    
    Console.WriteLine("The greatest of the numbers is {0}.", greatestValue);
  }
}


(The statement Console.Write, used in the example above, writes a text without advancing to the next line, so that the next text written will be exactly after this one).


A second example, to add or subtract two numbers depending on which option is chosen, it would be:

/*---------------------------*/
/*  C# Example #13:          */
/*  example13.cs             */
/*                           */
/*  Conditional operator - 2 */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example13
{
  public static void Main()
  {
    int a, b, operation, result;

    Console.Write("Enter a number: ");
    a = Convert.ToInt32(Console.ReadLine());

    Console.Write("Enter another: ");
    b = Convert.ToInt32(Console.ReadLine());   

    Console.Write("Choose an operation (1 = subtraction; other = addition): ");
    operation = Convert.ToInt32(Console.ReadLine());
   
    result = (operation == 1) ?  a-b : a+b;
    Console.WriteLine("The result is {0}.\n", result);
  }
}

Suggested exercises:
·       Create a program that uses the conditional operator to show the absolute value of a number as follows: if the number is positive, it will be is shown as is; if it is negative, it will be shown with its sign changed.
·       Use the conditional operator to calculate the lesser of two numbers.


No comments:

Post a Comment