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 **************************************/ #include <stdio.h> #include <math.h> int main() { // declare variables float l, b, a, p, d; // take input printf("Enter the length of rectangle: "); scanf("%f", & l); printf("Enter the breadth of rectangle: "); scanf("%f", & b); // calculate area a = l * b; // calculate perimeter p = 2 * (l + b); // calculate diagonal d = sqrt(l * l + b * b); // display result upto 3 decimal places printf("Area: %0.3f\n", a); printf("Perimeter: %0.3f\n", p); printf("Diagonal: %0.3f\n", d); return 0; }
Output
Enter the length of rectangle: 10.5
Enter the breadth of rectangle: 7
Area: 73.500
Perimeter: 35.000
Diagonal: 12.619