Q:

Kotlin program to find factorial of a given number using recursion

belongs to collection: Kotlin Recursion Programs

0

Given a number, we have to find its factorial using recursion.

Example:

    Input:
    5

    Output:
    120

All Answers

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

Program to find factorial of a given number using recursion in Kotlin

package com.includehelp.basic

import java.util.*

//function to calculate factorial using recursion
fun findFactorial(number:Int):Int{
    return if (number > 1) number * findFactorial(number - 1) else 1
}

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

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

    //Number should be Non Negative
    if(number>=0){
        //Call function to find out sum of all numbers up to given number
        var sum= findFactorial(number)

        //Print Sum
        println("Factorial of $number is : $sum")
    }
    else{
        System.err.println("Factorial of $number not Exist")
    }
}

Output

Run 1:
Enter Number  : 5
Factorial of 5 is : 120
---
Run 2:
Enter Number  : 0
Factorial of 0 is : 1
---
Run 3:
Enter Number  : -4
Factorial of -4 not Exist
---
Run 4:
Enter Number  : 9
Factorial of 9 is : 362880

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

total answers (1)

Kotlin program to find GCD/HCF of two numbers usin... >>
<< Kotlin program to find sum of natural numbers from...