Java Program to calculate the area of a circle.
Objective
Write a Java program to calculate the area of a circle given its radius.
Algorithm / Approach
- Prompt the user to enter the radius of the circle.
- Calculate the area using the formula
Area = 3.14 * r * r. - Store the result in a
doublevariable. - Print the result.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Radius:");
int r = s.nextInt();
double ar = 3.14*r*r;
System.out.println("Area = "+ar);
}
}
Expected Output
Enter Radius:7 Area = 153.86
Explanation of the Program
- The program prompts the user for the radius
r. - It calculates the area using the formula
π × r2, approximated as3.14 * r * r. - The resulting area is stored in a
doublevariablear. - The calculated area is then printed to the console.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Using an integer for the area, which truncates the decimal part of the result.
- Using
r + rinstead ofr * r.