GateAI
Programming in C

GATE CSE 2018 · Q21

NAT1 markEasy

Time

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

Your answerNumerical answer

Enter a value to check

Solution

Step-by-step verified solution

Official answer: 4

Programming in C

Let us trace the recursive calls to function calc(a, b) starting with calc(4, 81):

  1. Call 1:calc(4, 81)

    • counter is incremented to 11.

    • Since b=81≠3b = 81 \neq 3, it executes the else branch and calls calc(4, 81 / 3)→\rightarrowcalc(4, 27).

  2. Call 2:calc(4, 27)

    • counter is incremented to 22.

    • Since b=27≠3b = 27 \neq 3, it executes the else branch and calls calc(4, 27 / 3)→\rightarrowcalc(4, 9).

  3. Call 3:calc(4, 9)

    • counter is incremented to 33.

    • Since b=9≠3b = 9 \neq 3, it executes the else branch and calls calc(4, 9 / 3)→\rightarrowcalc(4, 3).

  4. Call 4:calc(4, 3)

    • counter is incremented to 44.

    • Since b=3==3b = 3 == 3, it enters the base case and returns 4×4×4=644 \times 4 \times 4 = 64 without making further recursive calls.

After all recursive calls complete, printf prints the final value of the global variable counter, which is 4.

Try the question first, then check your work.

Think the official key or this write-up is wrong?

Report error or challenge

Examiner trap

The misconception this question tests

This Programming in C previous year question is Q21 of the GATE CSE 2018 paper. Find more GATE CSE PYQs on Programming in C in Programming and Data Structures, or browse all GATE CSE PYQs.

Free diagnostic

Where do you stand for GATE?

Take the 20-minute diagnostic: the 3 topics that cost you the most marks, and a rank range. Or sit 5 related Programming in C PYQs now with no account.

One GATE CSE PYQ every morning

An official question by email at 7 AM IST, with a link to its verified solution. Unsubscribe in one click.

Programming in C in GATE CSE

Programming in C has 74 GATE CSE PYQs across 25 papers from 2011 to 2026. 16 of them are 1-mark NAT questions like this one, and GATE CSE 2018 has 2.

How GATE tests Programming in C

More from GATE CSE 2018

Share this solution

A plain-text card for WhatsApp or Telegram study groups.

GateAI solution cardGATE CSE 2018 · Q21 · NAT

Consider the following C program: #include 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 …

Topic-wise GATE CS PYQs with verified steps

Independent practice explanation verified by the GateAI team. GATE is conducted by the IITs; question text follows the official paper.