Skip to content
GATEiit

GATE CSE 2018 Q31: Number of recursive calls counted in a C program

Syllabus topics: Recursion; Programming in C

Question

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 _____.

Try it: numerical answer: type the value

Numerical answer. No negative marking.
Show answer and explanation

Answer: 4 (official GATE 2018 final answer key)

Concept used: Tracing recursion: counter is incremented once per call, and b is divided by 3 on each call until it reaches 3.

Concept notes

Loading notes…

First step: List the calls made: calc(4, 81), then the value of b in each following call until the base case b == 3.

Full step-by-step solution

Loading…

Answer from the official final answer key. Found a mistake? Use Report issue and we will fix it.

More questions on Recursion

Every PYQ on this topic →

Share this question

WhatsAppDownload image

Source: official GATE 2018 CS question paper and final answer key, organised by IIT Guwahati. Question paper · Answer key