Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 31

    Module 1 · Recursion Fundamentals · Lesson 1 of 31

    What recursion is, with your first function traced

    Work this problem first

    Trace SumTo(3) without running it. Write each call that is waiting, the first value returned, and the three additions in their execution order. Then state the supported input domain. A correct arithmetic result does not establish a safe recursion depth.

    Predict before running

    For this nonnegative SumTo recurrence, the call for n=3 has just received 3 from SumTo(2). What does it do next?

    A Return 3 unchanged.
    B Add its own n=3 and return 6.
    C Restart SumTo(3).
    D Add every waiting n in one parallel operation.
    Show answer

    Correct answer: B

    Each activation combines its own n with the child result after that child returns. The three additions occur during unwinding; the trace does not imply parallel execution.

    Hint: Read the return expression in the activation whose n is 3.

    The one-sentence definition

    A recursive function solves a problem by calling itself on a smaller version of the same problem, until the problem is so small that the answer is obvious.

    That is all of recursion: pass a smaller question forward, combine the answer on the way back.

    The two parts every recursive function needs

    PartSumTo contract
    Base casen=0 returns 0 without another recursive call
    Recursive casen>0 calls SumTo(n−1), then adds n after that result returns

    For this terminating-recursion pattern, every path must reach a base case by making progress in a well-founded measure (such as remaining items or subtree size). A missing stop condition or a call that fails to progress can lead to unbounded recursion. A genuine runtime stack-exhaustion failure in modern .NET normally terminates the process and cannot ordinarily be recovered with try/catch; this differs from manually throwing a StackOverflowException object. Even correct recursion can exhaust the stack on a sufficiently deep valid input. Build the habit: write the base case and explain why each recursive step approaches it.

    Your first function: SumTo(n)

    We want 1 + 2 + ... + n. The recursive insight is that the sum up to n is n plus the sum up to n - 1. The sum up to 0 is 0, and that is the base case. The sample assumes n >= 0 and a result fitting int: mathematically that permits n <= 65,535, but it does not guarantee the available stack can support that depth. Use small inputs for this teaching example; reject invalid inputs and choose an iterative or widened closed-form implementation when large n is required.

    C#
    static int SumTo(int n)
    {
        if (n == 0) return 0;          // base case
        return n + SumTo(n - 1);       // recursive case: shrink, trust, combine
    }

    What the call stack does

    Conceptually, each active invocation has its own frame holding its arguments and local state. The physical representation can be optimized by the compiler/JIT; the important model here is the distinct state that must remain available while a recursive call is pending. When SumTo(4) calls SumTo(3), the frame for SumTo(4) does not disappear. It pauses at the line where it made the call and waits. Only when the inner call returns does it resume and finish its own work.

    So a recursive call has two phases:

    1. Winding (going down). Frames pile up: SumTo(4) waits for SumTo(3), which waits for SumTo(2), and so on until the base case.
    2. Unwinding (coming back up). The base case returns, and each paused frame resumes in reverse order, adds its own n, and returns.

    The important consequence: the recursive call is not a loop reusing one variable. It is several paused copies of the method, each with its own n.

    Worked example: watching the stack (.NET 10)

    The program below adds depth and console tracing to expose the recurrence. The arithmetic is the same, but constructing/retaining indentation strings and writing output adds significant cost (see below). Factorial uses the same shape with multiplication. Its mathematical domain is nonnegative n; the long result is exact only for 0 <= n <= 20. The sample does not validate these contracts: its n <= 1 guard would return 1 for negative input even though that is not a valid factorial.

    C#
    // L01: SumTo(n) and Factorial(n), traced frame by frame on the call stack.
    Console.WriteLine($"SumTo(4) = {SumTo(4, 0)}");
    Console.WriteLine();
    Console.WriteLine($"Factorial(5) = {Factorial(5)}");
    Console.WriteLine($"Factorial(20) = {Factorial(20)}  (the largest n! that fits in a long)");
    
    static int SumTo(int n, int depth)
    {
        string pad = new(' ', depth * 2);
        if (n == 0)                       // base case: answered directly
        {
            Console.WriteLine($"{pad}SumTo(0) -> base case, returns 0");
            return 0;
        }
        Console.WriteLine($"{pad}SumTo({n}) pauses, waiting for SumTo({n - 1})");
        int smaller = SumTo(n - 1, depth + 1);   // recursive case: a smaller problem
        int result = n + smaller;                // combine on the way back up
        Console.WriteLine($"{pad}SumTo({n}) resumes: {n} + {smaller} = {result}");
        return result;
    }
    
    static long Factorial(int n) => n <= 1 ? 1 : n * Factorial(n - 1);

    Real output:

    Text
    SumTo(4) pauses, waiting for SumTo(3)
      SumTo(3) pauses, waiting for SumTo(2)
        SumTo(2) pauses, waiting for SumTo(1)
          SumTo(1) pauses, waiting for SumTo(0)
            SumTo(0) -> base case, returns 0
          SumTo(1) resumes: 1 + 0 = 1
        SumTo(2) resumes: 2 + 1 = 3
      SumTo(3) resumes: 3 + 3 = 6
    SumTo(4) resumes: 4 + 6 = 10
    SumTo(4) = 10
    
    Factorial(5) = 120
    Factorial(20) = 2432902008176640000  (the largest n! that fits in a long)

    Reading the output

    • The indentation represents recursive depth. Five invocations are active at the deepest point, SumTo(4) through SumTo(0); this is a conceptual call trace, not a measurement of JIT-generated physical stack frames.
    • Every "pauses" line has a matching "resumes" line, in the reverse order. This is last-in, first-out: the call stack is a stack.
    • The combining (n + smaller) happens only on the way back up. Nothing is added while going down.
    • Factorial(20) is the largest factorial that fits in a long. In an unchecked build, Factorial(21) wraps the long result; checked arithmetic inside the multiplication (or an applicable project setting) throws instead. A checked block around only the caller does not change arithmetic inside Factorial. BigInteger can represent larger results, but does not remove recursion-depth limits or make growing-number arithmetic constant-cost. Interviewers like this follow-up because it tests whether you think about the result type, not just the recursion.

    Compare your trace

    Returning callValue received from its childValue returned
    SumTo(0)No child call0
    SumTo(1)01
    SumTo(2)13
    SumTo(3)36

    How to hand-trace in an interview

    When asked "what does this return?", do not try to hold the whole thing in your head. Write two columns:

    Going downComing back up
    SumTo(4) waits for SumTo(3)SumTo(0) returns 0
    SumTo(3) waits for SumTo(2)SumTo(1) returns 1 + 0 = 1
    SumTo(2) waits for SumTo(1)SumTo(2) returns 2 + 1 = 3
    SumTo(1) waits for SumTo(0)SumTo(3) returns 3 + 3 = 6
    SumTo(0) is the base caseSumTo(4) returns 4 + 6 = 10

    Two to five rows like this are enough to show the interviewer you understand the mechanics. For anything deeper you switch to the leap of faith, which is the next lesson.

    Cost of this function

    • Untraced SumTo: one call per value n through 0: O(n) time and O(n) active-call storage under the usual fixed-width arithmetic model. A simple loop uses O(1) auxiliary space.
    • The displayed tracing program is different: at depth d it builds a 2d-character indentation string. Summed over depths 0..n, that is n(n+1) indentation characters constructed. Ancestor pad strings are needed again after the recursive call returns, so the straightforward implementation can retain O(n²) indentation characters at the deepest point, beyond its O(n) call stack. Trace construction/output therefore has quadratic character work, not the untraced linear cost.
    • Large inputs: iteration avoids deep calls; widening arithmetic or BigInteger addresses numeric range, a separate issue from stack depth.

    Common interview questions

    "Why not just use a loop here?" For SumTo a loop is better: it is just as clear and uses constant memory. SumTo is a teaching example. Recursion earns its place when the problem itself is recursive (trees, nested data, "try every option" searches). When to use recursion and when to prefer a loop covers the decision in detail.

    "What happens with a negative n?" SumTo(-1) moves away from the intended base case and will normally exhaust the stack. Validate with ArgumentOutOfRangeException.ThrowIfNegative(n) for the stated nonnegative domain. Using n <= 0 as a base case instead defines a different policy (all negative inputs return 0); it is not a substitute for deciding the input contract.

    "Is the order of the two parts important?" In this SumTo, check n == 0 before recursing on that path. Calling SumTo(n - 1) first would recurse again even at n == 0 instead of terminating there.

    Transfer drill: attempt before checking

    Explain why Factorial(21) needs a numeric-policy change even if all recursive calls fit the stack. Would putting only its caller inside checked repair the existing helper?

    Write your reasoning and a boundary test before reading the answer.

    Check your reasoning

    21! exceeds long.MaxValue. Checked arithmetic must cover the multiplication inside the helper, or the implementation needs another supported range/representation such as BigInteger. A checked caller does not change arithmetic inside a separately defined method. Stack depth remains a separate limit.

    Course prerequisites

    This course builds on basic C# syntax and collections. Use DSA Coding Patterns in C# for a traversal or collection refresher. Here, practise recurrence design, dependency order and constrained search. Numeric grouping in N0-formatted output follows your current culture; the arithmetic results remain the same.

    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·