Exercise
Conditional Operator, Positive & Smaller
Objective
Write a C# program that asks the user for two numbers and answers, using the conditional operator (?), for the following:
If the first number is positive
If the second number is positive
If both are positive
Which one is smaller
Write Your C# Exercise
C# Exercise Example
using System; // Import the System namespace which contains fundamental classes
class Program // Define the Program class
{
static void Main() // The entry point of the program
{
// Ask the user to enter the first number
Console.Write("Enter the first number: ");
int num1 = int.Parse(Console.ReadLine()); // Read and convert the input into an integer
// Ask the user to enter the second number
Console.Write("Enter the second number: ");
int num2 = int.Parse(Console.ReadLine()); // Read and convert the input into an integer
// Use the conditional operator to check if the first number is positive
string result1 = (num1 > 0) ? "The first number is positive." : "The first number is not positive.";
Console.WriteLine(result1); // Display the result for the first number
// Use the conditional operator to check if the second number is positive
string result2 = (num2 > 0) ? "The second number is positive." : "The second number is not positive.";
Console.WriteLine(result2); // Display the result for the second number
// Use the conditional operator to check if both numbers are positive
string result3 = (num1 > 0 && num2 > 0) ? "Both numbers are positive." : "At least one number is not positive.";
Console.WriteLine(result3); // Display the result if both numbers are positive
// Use the conditional operator to check which number is smaller
string smaller = (num1 < num2) ? "The first number is smaller." : (num2 < num1) ? "The second number is smaller." : "Both numbers are equal.";
Console.WriteLine(smaller); // Display the result for the smaller number
}
}