Java Program to Calculate Area, Perimeter and Diagonal of a Rectangle

Area, Perimeter and Diagonal and of Rectangle

Java 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. Java Program & Output to calculate area, perimeter and diagonal of a rectangle

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

import java.util.Scanner;
import java.lang.Math;

class Main {
    public static void main(String args[]) {
        // declare instance of Scanner class
        Scanner sc = new Scanner(System.in);

        // declare variables
        double l, b, a, p, d;

        // take input
        System.out.print("Enter the length of rectangle: ");
        l = sc.nextDouble();
        System.out.print("Enter the breadth of rectangle: ");
        b = sc.nextDouble();

        // 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
        System.out.println("Area: " + Math.round(a * 1000) / 1000.0);
        System.out.println("Perimeter: " + Math.round(p * 1000) / 1000.0);
        System.out.println("Diagonal: " + Math.round(d * 1000) / 1000.0);
    }
}

Output


Enter the length of rectangle: 6

Enter the breadth of rectangle: 3

Area: 18.0

Perimeter: 18.0

Diagonal: 6.708