Kotlin: Calculate the Area of a Circle

1. Introduction

Kotlin stands out in the realm of programming languages due to its simplicity, modernity, and enhanced functionalities. A popular choice for Android development, it also shines for basic computational tasks. Today, we’ll create a Kotlin program that calculates the area of a circle based on a given radius.

2. Program Overview

Our Kotlin journey will:

1. Prompt the user to input the radius of the circle.

2. Grab the radius provided by the user.

3. Compute the area of the circle using the formula \( Area = \pi * radius^2 \).

4. Showcase the calculated area to the user.

3. Code Program

import java.util.Scanner

fun main() {
    // Initiate a Scanner object to facilitate user input
    val reader = Scanner(System.in)
    
    // Ask the user to furnish the radius of the circle
    print("Please enter the radius of the circle: ")
    
    // Capture and save the provided radius
    val radius = reader.nextDouble()
    
    // Ensure the radius is positive
    if (radius < 0) {
        println("Please enter a positive radius.")
        return
    }
    
    // Calculate the area of the circle
    val area = Math.PI * radius * radius
    
    // Reveal the computed area to the user
    println("The area of a circle with radius $radius is: $area")
}

Output:

Please enter the radius of the circle: 5
The area of a circle with radius 5.0 is: 78.53981633974483

4. Step By Step Explanation

1. Scanner Object Creation: The Scanner class from the java.util package is employed to intake user input. reader is the name of our instance here.

2. Radius Acquisition: With the print function, the user is prompted to provide the circle's radius. This value is then fetched using reader.nextDouble() and saved in the variable named radius.

3. Positive Radius Check: Before delving into the calculation, it's essential to ensure the provided radius is non-negative. If a negative radius is detected, an error message gets displayed.

4. Area Calculation: The circle's area is determined using the formula \( Area = \pi * radius^2 \). Kotlin’s standard library gives us the constant Math.PI for an accurate representation of \(\pi\).

5. Result Presentation: The println function then displays the area to the user, rounding it to the default number of decimal places provided by the Double data type.

Comments