w3resource

Kotlin nested function: Calculate the square of a number

Kotlin Function: Exercise-20 with Solution

Write a Kotlin function inside another function that calculates the square of a number.

Sample Solution:

Kotlin Code:

fun calculatePower(number: Int): Int {
    fun calculateSquare(): Int {
        return number * number
    }
    
    return calculateSquare()
}

fun main() {
    val number = 7
    val square = calculatePower(number)
    println("Square of $number: $square")
}

Sample Output:

Square of 7: 49

Explanation:

In the above exercise -

  • The "calculatePower()" function takes an integer number as an argument. Inside this function, we define another function "calculateSquare()", which doesn't take any arguments. The "calculateSquare()" function simply calculates the square of the number by multiplying it by itself.
  • The calculatePower function then calls the nested function "calculateSquare()" and returns its result.
  • In the main function, we demonstrate the calculatePower function by passing a number and assigning the result to the variable square.

Kotlin Editor:


Previous: Check if the number is divisible.
Next: Swap variable values.

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.