Back to questions
JuniorTheoryCommon
What does the program print?
public class Main {
static int f(int n) {
return n == 0 ? 0 : n + f(n - 1);
}
public static void main(String[] args) {
System.out.println(f(4));
}
}10
- Expecting
0: the base case's 0 goes back tof(1), not tomain; each waiting call adds its ownn, so the answers grow to 1, 3, 6 and 10. - Expecting a
StackOverflowError:nreaches 0, and the?:returns 0 there without another call, so the chain stops after five calls.
- What happens if the program calls
f(-1)? - How would you compute the same sum with a loop?