Back to questions
JuniorTheoryCommon
What does the program print?
func sum(_ n: Int) -> Int {
if n == 1 {
return 1
}
return n + sum(n - 1)
}
print(sum(4))10
- Expecting
4: thinking all the calls share onen. Each call gets its own copy ofn, sosum(4)still adds4aftersum(3)returns. - Expecting
1: thinking the base case's value goes straight toprint.sum(1)returns tosum(2), and each call on the way back adds its ownn.
- What happens if you call
sum(0)with this function, and how would you fix it? - How would you write the same sum with a loop instead of recursion?