Skip to content
GATEiit

GATE CSE 2019 Q36: Recursive convert(n) with n/2 and n%2: behaviour for positive n

Syllabus topics: Recursion; Programming in C

Question

Consider the following C function.

void convert(int n){
    if(n<0)
        printf("%d",n);
    else {
        convert(n/2);
        printf("%d",n%2);
    }
}

Which one of the following will happen when the function convert is called with any positive integer n as argument?

Try it: multiple choice: exactly one correct option

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

Answer: D (official GATE 2019 final answer key)

Concept used: A recursion terminates only if its base case is reached; here n/2 reaches 0 and never becomes negative, and the prints come after the recursive call.

Concept notes

Loading notes…

First step: Trace the arguments n,n/2,n/4,… and check whether the condition n<0 is ever met, and whether any printf runs before the recursive call 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 2019 CS question paper and final answer key, organised by IIT Madras. Question paper · Answer key