Kotlin Program to Reverse a Sentence Using Recursion. Recursive function (reverse) takes string pointer (str) as input and calls itself with the next location to passed pointer (str+1).
Kotlin Program to Reverse a Sentence Using Recursion
Source Code
fun main(args: Array<String>) {
val sentence = "Go work"
val reversed = reverse(sentence)
println("The reversed sentence is: $reversed")
}
fun reverse(sentence: String): String {
if (sentence.isEmpty())
return sentence
return reverse(sentence.substring(1)) + sentence[0]
}
Output
Kotlin Program to Reverse a Sentence Using Recursion