w3resource

Kotlin program: Calculate circle area and perimeter


Write a Kotlin program to calculate the area and perimeter of a circle.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Command-Line Arguments.
  • Type Conversion.
  • Mathematical Operations.
  • Circle Formulas.
  • Error Handling.
  • String Interpolation.

Hints (Try before looking at the solution!)

  • Define the main() Function.
  • Prompt for Input.
  • Convert Input to Number.
  • Create Calculation Functions.
  • Call the Functions.
  • Display the Output.
  • Handle Invalid Input.
  • Test with Different Radii.
  • Common Errors to Avoid:
    • Forgetting to validate input.
    • Misplacing operators in formulas.
    • Not handling invalid inputs gracefully.

Sample Solution:

Kotlin Code:

import kotlin.math.PI

fun main(args: Array) 
  {
    println("Input the radius of the circle:")
    val radius = args[0].toDoubleOrNull()

    if (radius != null && radius > 0) 
      {
        val area = calculateArea(radius)
        val perimeter = calculatePerimeter(radius)

        println("Radius of the circle: $radius")
        println("Area of the circle: $area")
        println("Perimeter of the circle: $perimeter")
     } 
      else 
      {
        println("Invalid input. Please enter a valid positive radius.")
     }
 }

fun calculateArea(radius: Double): Double {
    return PI * radius * radius
}

fun calculatePerimeter(radius: Double): Double {
    return 2 * PI * radius
}

Sample Output:

Input the radius of the circle:
Radius of the circle: 5.2
Area of the circle: 84.94866535306801
Perimeter of the circle: 32.67256359733385

Kotlin Editor:


Previous: Check if a year is a leap year.
Next: Kotlin Program for Celsius to Fahrenheit and Vice Versa.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.