The GATE Grind

GATE 2018 CS – Question 31

Programming and Data Structures · Recursion · 1 mark · Numerical answer

Consider the following 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 ________.

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 4

Explanation

Each call of `calc(a, b)` increments `counter`, then either returns (if `b==3`) or calls `calc(a, b/3)`.

callb
181
227
39
43 (stops)

So `calc` is called 4 times and `counter` $=\mathbf4$.

More Recursion questions

All Recursion questions →