0
0
KotlinProgramBeginner · 2 min read

Kotlin Program to Find Area of Circle

To find the area of a circle in Kotlin, use val area = Math.PI * radius * radius where radius is the circle's radius.
📋

Examples

Inputradius = 0
OutputArea of circle is 0.0
Inputradius = 5
OutputArea of circle is 78.53981633974483
Inputradius = 10.5
OutputArea of circle is 346.3605900582744
🧠

How to Think About It

To find the area of a circle, you need the radius. The formula is area = π × radius × radius. First, get the radius value, then multiply it by itself and by π (pi).
📐

Algorithm

1
Get the radius value from the user or set it directly.
2
Calculate the area using the formula area = π × radius × radius.
3
Print or return the calculated area.
💻

Code

kotlin
fun main() {
    val radius = 5.0
    val area = Math.PI * radius * radius
    println("Area of circle is $area")
}
Output
Area of circle is 78.53981633974483
🔍

Dry Run

Let's trace the example where radius = 5.0 through the code

1

Set radius

radius = 5.0

2

Calculate area

area = 3.141592653589793 * 5.0 * 5.0 = 78.53981633974483

3

Print result

Output: Area of circle is 78.53981633974483

radiusarea
5.078.53981633974483
💡

Why This Works

Step 1: Using the radius

The radius is the distance from the center of the circle to its edge, needed for the area calculation.

Step 2: Applying the formula

The formula area = π × radius × radius calculates the space inside the circle.

Step 3: Using Math.PI

Kotlin's Math.PI provides a precise value of π for accurate calculation.

🔄

Alternative Approaches

Using a function to calculate area
kotlin
fun areaOfCircle(radius: Double): Double {
    return Math.PI * radius * radius
}

fun main() {
    val radius = 7.0
    println("Area of circle is ${areaOfCircle(radius)}")
}
This approach improves code reuse and clarity by separating calculation from input/output.
Using Kotlin's kotlin.math.PI constant
kotlin
import kotlin.math.PI

fun main() {
    val radius = 3.0
    val area = PI * radius * radius
    println("Area of circle is $area")
}
Using kotlin.math.PI is more idiomatic and recommended over Math.PI.

Complexity: O(1) time, O(1) space

Time Complexity

The calculation uses a fixed number of operations regardless of input size, so it is O(1).

Space Complexity

Only a few variables are used, so space complexity is O(1).

Which Approach is Fastest?

All approaches perform the same constant-time calculation; using a function improves readability but does not affect speed.

ApproachTimeSpaceBest For
Direct calculationO(1)O(1)Simple quick calculation
Function methodO(1)O(1)Reusable and clear code
Using kotlin.math.PIO(1)O(1)Idiomatic Kotlin code
💡
Use kotlin.math.PI for a more idiomatic Kotlin constant for π.
⚠️
Forgetting to square the radius and just multiplying by π once.