Home »
Kotlin »
Kotlin Programs »
Kotlin Basic Programs
Kotlin program to find factorial of a given number using recursion
Kotlin | Factorial program: Here, we are going to learn how to find factorial of a given number using recursion in Kotlin programming language?
Submitted by IncludeHelp, on April 27, 2020
Kotlin - Find factorial of a given number using recursion
Given a number, we have to find its factorial using recursion.
Example:
Input:
5
Output:
120
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