Programming Course in C# ¡Free!

Conditional operator

 Friday, April 05, 2013 published by Exercises C#
Proposed exercise

Create a program which assigns a integer variable "amountOfPositives" the value 0, 1 or 2, depending on the values of two numbers a & b (entered by the user).

Do it in two different ways: first using "if" and then using the "conditional operator" (?)


Output



Solution


using System;
public class Conditional
{
public static void Main()
{
int amount;

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

Console.Write("Enter second number: ");
int b = Convert.ToInt32(Console.ReadLine());

if ( (a > 0) && (b > 0) )
amount = 2;
else
{
if ( (a > 0) || (b > 0) )
amount = 1;
else
amount = 0;
}

Console.WriteLine("{0}", amount);

amount = ((a > 0) && (b > 0)) ? 2 :
((a > 0) || (b > 0)) ? 1 : 0;
Console.WriteLine("{0} positives.", amountOfPositives);
}
}