Q:

Kotlin program to calculate the power of a number using recursion

belongs to collection: Kotlin Recursion Programs

0

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

Example:

    Input:
    base = 2
    power = 3

    Output:
    8

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin program to find sum of natural numbers from... >>