Objective
Write a C# program to calculate (and display) the absolute value of a number x: if the number is positive, its absolute value is exactly the number x; if it's negative, its absolute value is -x.
Do it in two different ways in the same program: using "if" and using the "conditional operator" (?)
Write Your C# Exercise
C# Exercise Example
using System; // Importing the System namespace to use Console functionalities
class Program
{
// Main method where the program execution begins
static void Main()
{
// Prompt the user to enter a number
Console.Write("Enter a number: ");
int x = int.Parse(Console.ReadLine()); // Read and convert the input to an integer
// Using if statement to calculate absolute value
int absoluteValueIf = x; // Initially assume the absolute value is x
if (x < 0) // Check if the number is negative
{
absoluteValueIf = -x; // If negative, make it positive by negating it
}
// Display the result using the 'if' method
Console.WriteLine($"Absolute value using 'if': {absoluteValueIf}");
// Using the conditional operator (?) to calculate absolute value
int absoluteValueConditional = (x < 0) ? -x : x; // If x is negative, make it positive using ? operator
// Display the result using the conditional operator method
Console.WriteLine($"Absolute value using conditional operator: {absoluteValueConditional}");
}
}