Skip to content
GATEiit

GATE CSE 2017 Session 1 Q46: foo(3) with val-- recursion and bar(3) with val-1: termination behaviour

Syllabus topics: Recursion; Programming in C

Question

Consider the C functions foo and bar given below:

int foo(int val) {
   int x = 0;
   while(val > 0) {
      x = x + foo(val--);
   }
   return val;
}

int bar(int val) {
   int x = 0;
   while(val > 0) {
      x = x + bar(val-1);
   }
   return val;
}

Invocations of foo(3) and bar(3) will result in :

Try it: multiple choice: exactly one correct option

Select one option
Wrong answer costs 2/3 mark in GATE.
Show answer and explanation

Answer: C (official GATE 2017 final answer key)

Concept used: Post-decrement passes the old value, so foo(val--) recurses on the same argument forever (stack overflow), while bar never changes its own val, so its while loop never ends once a recursive call returns.

Concept notes

Loading notes…

First step: Note what argument foo(val--) actually passes, and for bar, see what happens in bar(1) after the call bar(0) returns.

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 2017 Session 1 CS question paper and final answer key, organised by IIT Roorkee. Question paper · Answer key