The area of a circle is calculated using the formula:
Area = π × r², where 'r' is the radius of the circle.
We will explore three different methods to calculate the area of a circle in Java programming.
This method directly computes the area using the formula.
import java.util.Scanner; public class CircleArea { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the radius of the circle: "); double radius = scanner.nextDouble(); double area = Math.PI * radius * radius; System.out.printf("Area of the circle: %.2f\n", area); scanner.close(); } }
This method uses a function to calculate and return the area.
import java.util.Scanner; public class CircleAreaFunction { static double calculateArea(double radius) { return Math.PI * radius * radius; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the radius of the circle: "); double radius = scanner.nextDouble(); System.out.printf("Area of the circle: %.2f\n", calculateArea(radius)); scanner.close(); } }
This method demonstrates recursion, though recursion is not typically needed for simple mathematical operations.
import java.util.Scanner; public class CircleAreaRecursion { static double recursiveArea(double radius, int times) { if (times == 0) { return Math.PI * radius * radius; } return recursiveArea(radius, times - 1); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the radius of the circle: "); double radius = scanner.nextDouble(); System.out.printf("Area of the circle: %.2f\n", recursiveArea(radius, 1)); scanner.close(); } }