In: Computer Science
Write a program that calculates the area and circumference of a circle. It should ask the user first to enter the number of circles n, then reads the radius of each circle and stores it in an array. The program then finds the area and the circumference, as in the following equations, and prints them in a tabular format as shown in the sample output. Area = πr2 , Circumference = 2πr, π = 3.14159
Sample Output:
Enter the number of circles: 4
Enter the radius of circle 1 : 10.5
Enter the radius of circle 2 : 5
Enter the radius of circle 3 : 30.7
Enter the radius of circle 4 : 12.5
(( in java ))
Answer:
import java.util.Scanner; //importing Scanner class for taking
the data from the keyboard
import java.text.DecimalFormat; //importing DecimalFormat class for
formatting the output
public class Circle //class Circle starts here
{
private static DecimalFormat df = new DecimalFormat("#.##"); /*
Object 'df' is created of class DecimalFormat and setting two
digits after the decimal point */
public static void main(String[] args) // main() function starts
here
{
double area,circumference; // variable declaration
int n; // variable declaration
Scanner s = new Scanner(System.in); // 's' is the object of Scanner
class
System.out.print("Enter the number of circles: "); // prompts the
message
n = s.nextInt(); // reads an integer from the keyboard and stores
in 'n' (no. of circles)
double a[] = new double[n]; // An array of double type is created
with size 'n'
for(int i = 0; i < n ; i++) // loop repeats for 'n' times
{
System.out.printf("Enter the radius of circle "+(i+1)+": "); //
prompts the message
a[i] = s.nextDouble(); // reading a double value from
the keyboard and storing in the array
}
for(int i = 0; i < n ; i++) // loop repeats for 'n' times
{
area = (3.14159*a[i]*a[i]); // calculates the area of (i+1)th
circle)
circumference = (2*3.14159*a[i]); //calculates the
circumference (i+1)th circle)
System.out.println("The area and circumference of
circle "+(i+1)+" is: "+df.format(area)+",
"+df.format(circumference));
/* displaying the area, circumference of (i+1)th
circle by rounding the result to 2 decimal places */
}
} // end of main()
} // end of class
Program Screenshot:
Output: