C++ Program to Calculate Area, Perimeter and Diagonal of a Rectangle

Area, Perimeter and Diagonal and of Rectangle

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. A := l * b

3. P := 2 * (l + b)

4. D := sqrt(l^2 + b^2)

5. Return A, P, D

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

Code has been copied
/*************************************
	  alphabetacoder.com
C++ program to calculate the area, 
perimeter and diameter of a rectangle
**************************************/

#include <iostream>
#include <cmath>

using namespace std;

int main() {
    // declare variables
    float l, b, a, p, d;

    // take input
    cout << "Enter the length of rectangle: ";
    cin >> l;
    cout << "Enter the breadth of rectangle: ";
    cin >> b;

    // calculate area
    a = l * b;
    // calculate perimeter
    p = 2 * (l + b);
    // calculate diagonal
    d = sqrt(l * l + b * b);

    // display result
    cout << "Area: " << a << endl;
    cout << "Perimeter: " << p << endl;
    cout << "Diagonal: " << d << endl;

    return 0;
}

Output


Enter the length of rectangle: 15

Enter the breadth of rectangle: 10

Area: 150

Perimeter: 50

Diagonal: 18.0278