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

Area Perimeter and Diagonal of Square

Java program to calculate the area, perimeter and diagonal of a square has been given below. If length of the side of a square is $s~ unit$, the area, perimeter and diagonal of that square would be $s^2~\text{unit}^2$, $4s~\text{unit}$ and $s\sqrt{2}~\text{unit}$ respectively.


For example, if length of the side of a square is $5~cm$, the area would be $5^2 = 25~\text{cm}^2$ while the perimeter would be $4 \cdot 5 = 20~\text{cm}$. The diagonal will be calculated as $5\cdot \sqrt{2} = 7.071 ~\text{cm}$


In the following section, the algorithm, pseudocode and time-complexity of the program have also been covered.





1. Algorithm to calculate the area, perimeter and diagonal of a square


1. Take the length of side $s$ as input.

2. Declare $s^2$ as the area of the square

3. Declare $4s$ as the perimeter of the square

4. Declare $s\sqrt{2}$ as the diagonal of the square




2. Pseudocode to calculate the area, perimeter and diagonal of a square


Input : Length of side $s$

Output : Area $A$, Perimeter $P$ and Diagonal $D$ of the square

1. Procedure areaPerimeterDiagonal($s$):

2. $A = s^2$

3. $P = 4s$

4. $D = s\sqrt{2}$

5. Return $A, P, D$

6. End Procedure





3. Time complexity to calculate the area, perimeter and diagonal of a square


Time Complexity: O(1)




4. Java Program to calculate the area, perimeter and diagonal of a square

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

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

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

        // declare instance of DecimalFormat class
        DecimalFormat obj = new DecimalFormat("#.###");

        // declare variables
        double s, a, p, d;

        // take input
        System.out.print("Enter the length of side of the square: ");
        s = sc.nextFloat();

        // calculate area
        a = s * s;
        // calculate perimeter
        p = 4 * s;
        // calculate diagonal
        d = s * Math.sqrt(2);

        // display result upto 3 decimal places
        System.out.println("Area: " + obj.format(a));
        System.out.println("Perimeter: " + obj.format(p));
        System.out.println("Diagonal: " + obj.format(d));
    }
}

Output


Enter the length of side of the square: 25

Area: 625

Perimeter: 100

Diagonal: 35.355