Recursive Functions
Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 44 of 63.
A recursive function calls itself on a smaller subproblem. A base case returns without another recursive call. For a countdown total, zero is the base case and n - 1 moves closer to it. Ordinary recursion uses call-stack space, so keep input depth small.
fun countdownSum(n: Int): Int {
if (n == 0) return 0
return n + countdownSum(n - 1)
}Inside main:
println(countdownSum(4))The calls add four, three, two and one, then stop at zero.
Recursion needs a reachable base case and progress toward it.
Challenge
MediumComplete recursiveSum with parameters number: Int. Using recursion, return the sum from 1 through number. number is between 0 and 100. The result for zero is zero.
Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.
Return a value of type Int. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.
Try it yourself
fun recursiveSum(number: Int): Int {
// Write your solution here.
return 0
}
fun main() {
val number = readln().toInt()
println(recursiveSum(number))
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
4Nested Collections
Lists of ListsTraversing RowsRow SummariesFlattening Nested ListsRecap - Seating Rows7Collection Pipelines
Transforming with MapFiltering ValuesTesting Collection RulesAccumulating with FoldRecap - Approved Totals5Project - Contact Book
Save ContactsFind Contacts6Function Values
Writing LambdasFunction TypesPassing FunctionsCaptured VariablesRecap - Configurable Score9Advanced Control Flow
Guard ClausesBreaking Labeled LoopsContinuing Labeled LoopsRecursive FunctionsRecap - First Valid RowPractice on your own: Kotlin playground