Java: Find the area and perimeter of a circle
Java Basic: Exercise-11 with Solution
Circle: Area and Perimeter
Write a Java program to print the area and perimeter of a circle.
In geometry, the area enclosed by a circle of radius r is πr2. Here the Greek letter π represents a constant, approximately equal to 3.14159, which is equal to the ratio of the circumference of any circle to its diameter.
The circumference of a circle is the linear distance around its edge.
Pictorial Presentation:
Why is the area of a circle of a circle pi times the square of the radius?
Sample Solution-1
Java Code:
public class Exercise11 {
// Define a constant for the radius of the circle
private static final double radius = 7.5;
public static void main(String[] args) {
// Calculate the perimeter of the circle using the constant radius
double perimeter = 2 * Math.PI * radius;
// Calculate the area of the circle using the constant radius
double area = Math.PI * radius * radius;
// Print the calculated perimeter and area
System.out.println("Perimeter is = " + perimeter);
System.out.println("Area is = " + area);
}
}
Explanation:
In the exercise above -
The above Java code calculates and prints the perimeter and area of a circle with a given radius (in this case, a radius of 7.5 units). It uses mathematical constants and formulas for circles:
- It calculates the perimeter (circumference) using the formula: 2 * Math.PI * radius;
- It calculates the area using the formula: π * radius^2.
The perimeter and area values are then printed to the console.
Sample Output:
Perimeter is = 47.12388980384689 Area is = 176.71458676442586
Flowchart:
Sample Solution-2
Java Code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner io = new Scanner(System.in);
// Prompt the user to input the radius of the circle
System.out.println("Input the radius of the circle: ");
// Read and store the input radius
double radius = io.nextDouble();
// Calculate and print the perimeter of the circle
System.out.println("Perimeter is = " + (2 * radius * Math.PI));
// Calculate and print the area of the circle
System.out.println("Area is = " + (Math.PI * radius * radius));
}
}
Sample Output:
Input the radius of the circle: 5 Perimeter is = 31.41592653589793 Area is = 78.53981633974483
Flowchart:
Java Code Editor:
Previous: Write a Java program to compute a specified formula.
Next: Write a Java program that takes five numbers as input to calculate and print the average of the numbers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/basic/java-basic-exercise-11.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics