Kotlin program to calculate the power of a number using recursion

Kotlin | Power calculation program: Here, we are going to learn how to calculate the power of a given number using recursion in Kotlin programming language? Submitted by IncludeHelp, on April 27, 2020

Kotlin - Calculate the power of a number using recursion

Given two numbers (base, power), we have to calculate base to the power of power.

Example:

Input:
base = 2
power = 3

Output:
8

Program to calculate the power of a number using recursion in Kotlin

package com.includehelp.basic

import java.util.*


//function to calculate power using recursion
fun calPower(baseValue: Int, powerValue: Int): Int {
    return if (powerValue != 0)  baseValue * calPower(baseValue, powerValue - 1) else 1
}

//Main Function entry Point of Program
fun main(args: Array<String>) {
    //Input Stream
    val scanner = Scanner(System.`in`)

    //input Base integer number
    print("Enter Base Number  : ")
    val base: Int = scanner.nextInt()


    //input Power integer number
    print("Enter Power Number  : ")
    val power: Int = scanner.nextInt()


    //Call function to Calculate Power using recursion
    val res = calPower(base,power)

    //Print Result
    println("$base^$power = $res")
}

Output

Run 1:
Enter Base Number  : 5
Enter Power Number  : 3
5^3 = 125
-------
Run 2:
Enter Base Number  : 6
Enter Power Number  : 4
6^4 = 1296
-------
Run 3:
Enter Base Number  : 7
Enter Power Number  : 0
7^0 = 1

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.