r/ProgrammerHumor • • Jun 16 '21

Maximum call stack size exceeded

Post image
20.2k Upvotes

225 comments sorted by

View all comments

30

u/GroundTeaLeaves Jun 16 '21

What is a base case?

56

u/TheHackPete Jun 16 '21 edited Jun 16 '21

(The) One case you know the answer for.

The other cases recurse toward the base case. This way, the calculation can stop.

e.g. you know the Fibonacci number of 0 and 1. Every other is the sum of the two predecessors. So fib(3) is fib(2)+fib(1); whith fib(2) being fib(1)+fib(0) and fib(1) and fib(0) being known --> the "base case(s)".

0

u/[deleted] Jun 16 '21

[deleted]

2

u/Gonimokon Jun 17 '21

Should be noted that implementation runs in O( 2n ) time.

16

u/CookieSpoder Jun 16 '21
public static long sumOfDigits(long n) {
    if (n==0) {
        return 0;
    } else {
        return n % 10 + sumOfDigits(n/10);
    }
}

The base case returns 0, like the other comment said, this is where the recursion ends. The base case is a final state that you know will inevitably happen. This method here sums the digits in a given number, ie 1 2 3 = 6. Any number less than 10 when divided by 10 will return 0. This lets the function know that it has reached the last digit, and the recursion ends.

5

u/cowlinator Jun 16 '21

When you know what recursion is, but you don't know what a base case is, your only option is stack overflow

2

u/[deleted] Jun 16 '21

Only option AND actual exception you’ll encounter

2

u/SonicSubculture Jun 16 '21

You could call it a… first order response

0

u/[deleted] Jun 16 '21

It's a case of the base type