Skip to main content

Direct and indirect recursion

Short answer

Direct recursion is a function calling itself, for example fact(n)=n*fact(n-1). Indirect recursion occurs when a function calls another function that eventually calls the first, forming a cycle such as isEven->isOdd->isEven. Direct is easier to trace; indirect is harder.

Explain direct and indirect recursion with suitable example.

Direct recursion

A function calls itself directly in its own body.

int fact(int n) {
    if (n == 0) return 1;
    return n * fact(n - 1);     /* fact calls fact */
}

Call chain: fact → fact → fact ...

Indirect recursion

A function calls another function, which in turn calls the first one again, forming a cycle (A → B → A). The self-call happens through other functions.

void funB(int n);
void funA(int n) {
    if (n > 0) { printf("%d ", n); funB(n - 1); }
}
void funB(int n) {
    if (n > 1) { printf("%d ", n); funA(n / 2); }
}

Call chain: funA → funB → funA → ... For funA(20) the output is 20 19 9 8 4 3 1.

DirectIndirect
Function calls itselfCalls through one or more other functions
Easy to understand and traceHarder to trace
Example: factorialExample: isEven/isOdd calling each other

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 5 questions →