Group
C# Basic Data Types Overview
Objective
Write a C# program that calculates the perimeter, area, and diagonal of a rectangle, given its width and height.
Hint: Use Math.Sqrt(x) to calculate the square root.
Example C# Exercise
Show C# Code
using System;
class Program
{
static void Main()
{
// Prompt the user to enter the width of the rectangle
Console.Write("Enter the width of the rectangle: ");
double width;
// Validate user input
while (!double.TryParse(Console.ReadLine(), out width) || width <= 0)
{
Console.Write("Invalid input. Please enter a positive number for the width: ");
}
// Prompt the user to enter the height of the rectangle
Console.Write("Enter the height of the rectangle: ");
double height;
// Validate user input
while (!double.TryParse(Console.ReadLine(), out height) || height <= 0)
{
Console.Write("Invalid input. Please enter a positive number for the height: ");
}
// Calculate the perimeter
double perimeter = 2 * (width + height);
// Calculate the area
double area = width * height;
// Calculate the diagonal using the Pythagorean theorem
double diagonal = Math.Sqrt((width * width) + (height * height));
// Display the results
Console.WriteLine("\nRectangle Properties:");
Console.WriteLine($"Perimeter: {perimeter}");
Console.WriteLine($"Area: {area}");
Console.WriteLine($"Diagonal: {diagonal:F2}"); // Display diagonal rounded to 2 decimal places
}
}
Output
//Example Execution 1:
Enter the width of the rectangle: 6
Enter the height of the rectangle: 8
Rectangle Properties:
Perimeter: 28
Area: 48
Diagonal: 10.00
//Example Execution 2:
Enter the width of the rectangle: 5.5
Enter the height of the rectangle: 3.2
Rectangle Properties:
Perimeter: 17.4
Area: 17.6
Diagonal: 6.30
//Example Execution 3 (Invalid Input Handling):
Enter the width of the rectangle: -4
Invalid input. Please enter a positive number for the width: 4
Enter the height of the rectangle: 0
Invalid input. Please enter a positive number for the height: 7
Rectangle Properties:
Perimeter: 22
Area: 28
Diagonal: 8.06