Write a Java program to input length and width and find perimeter and area of rectangle. Logic to find perimeter and area of a rectangle, whose length and width are given. In this example we will learn to write basic logical program in Java. We will learn to find perimeter and area of rectangle.
Example
Input
Input
Length of rectangle = 30 Width of rectangle = 20
Output
Perimeter of rectangle is 100.0 units. Area of rectangle is 600.0 sq. units.
Required knowledge
Arithmetic operators, Data types, Basic input/output
Logic to find perimeter and area of a rectangle
Step by step descriptive logic to find perimeter and area of a rectangle.
- Input length and width of rectangle from user. Store it in some variable say length and width.
- Apply formula to calculate rectangle perimeter i.e.
perimeter = 2 * (length + width)
. - Apply formula to calculate rectangle area i.e.
area = length * width
. - Finally, print the value of perimeter and area.
Program to find perimeter and area of rectangle
/**
* Java program to find perimeter and area of a rectangle.
*/
import java.util.Scanner;
public class Rectangle {
public static void main(String[] args) {
float length, width, area, perimeter;
// Create scanner class object
Scanner in = new Scanner(System.in);
// Input length and width of rectangle
System.out.print("Enter length of rectangle: ");
length = in.nextFloat();
System.out.print("Enter width of rectangle: ");
width = in.nextFloat();
// Calculate perimeter of rectangle
perimeter = 2 * (length + width);
// Calculate area of rectangle
area = length * width;
// Print perimeter and area of rectangle
System.out.println("Perimeter of rectangle is " + perimeter + " units.");
System.out.println("Area of rectangle is " + area + " sq. units.");
}
}
Output
Enter length of rectangle: 30 Enter width of rectangle: 20 Perimeter of rectangle is 100.0 units. Area of rectangle is 600.0 sq. units.
Happy coding 😉