Objective
Write a C# program to calculate the perimeter, area and diagonal of a rectangle from its width and height (perimeter = sum of the four sides, area = base x height, diagonal using the Pythagorean theorem). It must repeat until the user enters 0 for the width.
Write Your C# Exercise
C# Exercise Example
using System; // Import the System namespace to use basic classes like Console and Math
class Program // Define the main class of the program
{
static void Main() // The entry point of the program
{
// Infinite loop to keep asking the user for input until they enter 0 for the width
while (true)
{
// Ask the user for the width of the rectangle
Console.Write("Enter the width of the rectangle (0 to quit): ");
double width = double.Parse(Console.ReadLine()); // Read the user's input and convert it to a double
// If the width is 0, exit the loop and end the program
if (width == 0)
{
Console.WriteLine("Goodbye!");
break; // Exit the while loop and end the program
}
// Ask the user for the height of the rectangle
Console.Write("Enter the height of the rectangle: ");
double height = double.Parse(Console.ReadLine()); // Read the user's input and convert it to a double
// Calculate the perimeter of the rectangle (sum of all sides)
double perimeter = 2 * (width + height);
// Calculate the area of the rectangle (base x height)
double area = width * height;
// Calculate the diagonal using the Pythagorean theorem (sqrt(width^2 + height^2))
double diagonal = Math.Sqrt(Math.Pow(width, 2) + Math.Pow(height, 2));
// Display the results
Console.WriteLine($"Perimeter: {perimeter}");
Console.WriteLine($"Area: {area}");
Console.WriteLine($"Diagonal: {diagonal}\n");
}
}
}