Skip to content
Official PYQ · 2018

GATE CS 2018 Q21 — Recursion

Explain with AI

Consider the following C\text{C} program:

#include<stdio.h>

int counter=0;

int calc (int a, int b) {
        int c;
        counter++;
        if(b==3) return (a*a*a);
        else {
                c = calc(a, b/3);
                return (c*c*c);
        }
}

int main() {
        calc(4, 81);
        printf("%d", counter);
}

The output of this program is ______.

View worked solution

Answer: 4

To find the output of the program, we trace the execution of the recursive function calc(4, 81) and track the value of the global variable counter.

The function calc(a, b) increments counter by 1 on every entry. Let's trace the sequence of recursive calls:

  1. First Call: calc(4, 81)
    • counter is incremented to 1.
    • Since b=81≠3b = 81 \neq 3, the else branch is executed.
    • It calls calc(4, 81/3), which is calc(4, 27).
  2. Second Call: calc(4, 27)
    • counter is incremented to 2.
    • Since b=27≠3b = 27 \neq 3, the else branch is executed.
    • It calls calc(4, 27/3), which is calc(4, 9).
  3. Third Call: calc(4, 9)
    • counter is incremented to 3.
    • Since b=9≠3b = 9 \neq 3, the else branch is executed.
    • It calls calc(4, 9/3), which is calc(4, 3).
  4. Fourth Call: calc(4, 3)
    • counter is incremented to 4.
    • Since b=3b = 3, the base condition if(b == 3) is satisfied.
    • It returns 43=644^3 = 64 and begins unwinding the recursion.

After all recursive calls complete and return, the final value of counter printed by the main function is 4.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Recursion questions