C# program to calculate area, perimeter and diagonal of a rectangle has been given below. Suppose, length and breadth of a rectangle are l unit, and b unit respectively. Then area, perimeter and diagonal of that rectangle would be l * b unit^2, 2 * (l + b) unit and sqrt(l^2 + b^2) unit, respectively.
For example, if length is 7 cm and breadth is 3 cm, then area of the rectangle would be 7 * 3 = 21 cm^2 while perimeter and diagonal would be 2 * (7 + 3) = 20 cm and sqrt(7^2 + 3^2) = sqrt(58) = 7.616 cm.
The algorithm, pseudocode, and time-complexity of the program have also been covered below.
1. Algorithm to calculate area, perimeter and diagonal of a rectangle
1. Take the length l and the breadth b of a rectangle as inputs.
2. Compute a = l * b
3. Compute p = 2 * (l + b)
4. Compute d = sqrt(l^2 + b^2)
5. Declare the a as the area, p as the perimeter and d as the diagonal of that rectangle.
2. Pseudocode to calculate area, perimeter and diagonal of a rectangle
Input : Length l and breadth b of a rectangle
Output : Area A, Perimeter P and Diagonal D of the rectangle
1. Procedure areaPerimeterDiagonal(l, w):
2.
3.
4.
5.
6. End Procedure
3. Time complexity to calculate area, perimeter and diagonal of a rectangle
Time Complexity: O(1)
4. C# Program & Output to calculate area, perimeter and diagonal of a rectangle
/************************************* alphabetacoder.com C# program to calculate the area, perimeter and diameter of a rectangle **************************************/ using System; namespace AreaPerimeterDiagonal { class Program { static void Main(string[] args) { // declare variables double l, b, a, p, d; // take input Console.Write("Enter the length of rectangle: "); l = Convert.ToDouble(Console.ReadLine()); Console.Write("Enter the breadth of rectangle: "); b = Convert.ToDouble(Console.ReadLine()); // calculate area a = l * b; // calculate perimeter p = 2 * (l + b); // calculate diagonal d = Math.Sqrt(l * l + b * b); // display result upto 3 decimal places Console.Write("Area: " + string.Format("{0:0.000}", a) + "\n"); Console.Write("Perimeter: " + string.Format("{0:0.000}", p) + "\n"); Console.Write("Diagonal: " + string.Format("{0:0.000}", d) + "\n"); // wait for user to press any key Console.ReadKey(); } } }
Output
Enter the length of rectangle: 8
Enter the breadth of rectangle: 5
Area: 40.000
Perimeter: 26.000
Diagonal: 9.434