📜  Kotlin 递归

📅  最后修改于: 2022-05-13 01:54:38.273000             🧑  作者: Mango

# Kotlin 递归

1. 普通函数调用
2. 递归函数调用

## 递归函数调用

``````// Kotlin program of factorial using recursion
fun Fact(num: Int):Long{
return  num*Fact(num-1)  // no terminate condition
}
//main method
fun main() {
println("Factorial of 5 is: "+Fact(5))
//Recursive call
}
``````

``Exception in thread "main" java.lang.StackOverflowError``

``````// Kotlin program of factorial using recursion
fun Fact(num: Int):Long{
return if(num==1) num.toLong()        // terminate condition
else num*Fact(num-1)
}
//main method
fun main() {
println("Factorial of 5 is: "+Fact(5))
//Recursive call
}
``````

``Factorial of 5 is: 120``

### 阶乘程序的工作 -

Fact() 的递归调用在下图中一步一步解释：-

``````// two parameters passed an array and size of array
fun sum(args: Array , index:Int ):Int{
return if(index<=0) 0
else (sum(args ,index-1) + args[index-1])      // recursive function call
}

fun main() {
// array initialization
val array = arrayOf(1,2,3,4,5,6,7,8,9,10)
// size of array
val n = array.size
val result = sum(array,n)             // normal function call
println("The sum of array elements is: \$result")
}
``````

``The sum of array elements is: 55``