Back to questions
JuniorTheoryCommon
What does the program print?
fun sumTo(n: Int): Int {
if (n == 0) return 0
return n + sumTo(n - 1)
}
fun main() {
println(sumTo(4))
}10
- Expecting
0: thinkingreturn 0in the base case ends everything. It answers onlysumTo(0); each waiting call then adds its ownnon the way back. - Expecting
24: reading the function as a product of the numbers. It adds with+and returns0at0, so the result is4 + 3 + 2 + 1 + 0.
- What happens if the line
if (n == 0) return 0is removed? - How many calls of
sumToare waiting at once whensumTo(0)runs?