Group
C# Flow Control Basics
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" (?).
Example C# Exercise
Show C# Code
using System;
namespace AbsoluteValueCalculator
{
class Program
{
static void Main(string[] args)
{
// Prompt the user to enter a number
Console.Write("Enter a number: ");
double x = double.Parse(Console.ReadLine()); // Read the number entered by the user
// Calculate the absolute value using 'if' statement
double absoluteValueIf = x;
if (x < 0)
{
absoluteValueIf = -x; // If the number is negative, negate it to get the absolute value
}
// Display the result using 'if' statement
Console.WriteLine("Using 'if': The absolute value of {0} is {1}", x, absoluteValueIf);
// Calculate the absolute value using the conditional operator (ternary operator)
double absoluteValueConditional = (x < 0) ? -x : x; // If x is negative, use -x, otherwise use x
// Display the result using the conditional operator
Console.WriteLine("Using conditional operator: The absolute value of {0} is {1}", x, absoluteValueConditional);
}
}
}
Output
//Example 1 (Positive Number):
Enter a number: 25
Using 'if': The absolute value of 25 is 25
Using conditional operator: The absolute value of 25 is 25
//Example 2 (Negative Number):
Enter a number: -12
Using 'if': The absolute value of -12 is 12
Using conditional operator: The absolute value of -12 is 12
//Example 3 (Zero):
Enter a number: 0
Using 'if': The absolute value of 0 is 0
Using conditional operator: The absolute value of 0 is 0