w3resource

Kotlin nested function: Calculate the square of a number


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


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax: Familiarity with writing and running Kotlin programs.
  • Kotlin Functions: Understanding how to define and call functions in Kotlin.
  • Nested Functions: Knowledge of defining a function inside another function and its scope limitations.
  • Arithmetic Operations: Ability to perform multiplication to calculate the square of a number.
  • Printing Output: Familiarity with the println() function to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Outer Function.
  • Define the Nested Function.
  • Call the Nested Function.
  • Call the Outer Function.
  • Display the Output.
  • Test with Different Numbers.
  • Common Errors to Avoid:
    • Forgetting nested function scope.
    • Misplacing arithmetic logic.
    • Not testing edge cases.

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.