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
Program to find factorial of a given number using recursion in Kotlin
Output
need an explanation for this answer? contact us directly to get an explanation for this answer