Skip to main content

How to calculate the cube of a number in Kotlin

How to calculate the cube of a number in Kotlin.

Here is a step-by-step tutorial on how to calculate the cube of a number in Kotlin:

Step 1: Define a function

To calculate the cube of a number, we can start by defining a function in Kotlin. The function will take an input number as a parameter and return the cube of that number. Here's how you can define the function:

fun calculateCube(number: Int): Int {
// code to calculate the cube of the number
}

Step 2: Calculate the cube

Inside the calculateCube function, we can calculate the cube of the input number using the formula number * number * number. Here's how you can implement it:

fun calculateCube(number: Int): Int {
return number * number * number
}

Step 3: Test the function

To ensure that our function works correctly, we can test it with some sample inputs. Here's an example:

fun main() {
val number = 5
val cube = calculateCube(number)
println("The cube of $number is $cube")
}

In this example, we have assigned the value 5 to the number variable. Then, we call the calculateCube function and pass number as an argument. The returned cube value is stored in the cube variable. Finally, we print the result using println.

Step 4: Run the program

To see the output, you can run the program. In Kotlin, you can either use an IDE like IntelliJ IDEA or run the program from the command line. After running the program, you should see the following output:

The cube of 5 is 125

This output confirms that our function is correctly calculating the cube of the input number.

Step 5: Handle negative numbers

If you want to handle negative numbers as input, you can modify the calculateCube function to handle both positive and negative numbers. Here's an updated version of the function:

fun calculateCube(number: Int): Int {
return if (number >= 0) {
number * number * number
} else {
-1 * number * number * number
}
}

In this updated version, if the input number is positive or zero, the cube is calculated as before. However, if the input number is negative, we multiply the cube by -1 to make it negative as well.

That's it! You have now learned how to calculate the cube of a number in Kotlin. You can use the calculateCube function in your Kotlin programs to compute the cube of any given number.