Consider the following ANSI C program #include <stdio.h> int foo(int x, int y,…

2021

Consider the following ANSI C program

#include <stdio.h>

int foo(int x, int y, int q)

{

if ((x<=0) && (y<=0))

return q;

if (x<=0)

return foo(x, y-q, q);

if (y<=0)

return foo(x-q, y, q);

return foo(x, y-q, q) + foo(x-q, y, q);

}

int main( )

{

int r = foo(15, 15, 10);

printf(“%d”, r);

return 0;

}

The output of the program upon execution is _________ .

Attempted by 134 students.

Show answer & explanation

Correct answer: 60

Answer: 60

Brief explanation: Each call subtracts q = 10 from either x or y. While both x and y remain positive the function branches into two calls. Once one coordinate becomes non-positive, further calls are forced along the other coordinate until both are non-positive, at which point the call returns q. So each termination path contributes q to the total, and we need to count how many distinct termination paths there are starting from (15,15).

  • Paths that terminate after two moves: reducing x twice (x→5→-5) or reducing y twice (y→5→-5). These are two distinct paths.

  • Paths that terminate after three moves: if the first two moves reduce different coordinates (one x and one y), the third move (either x or y) will make one coordinate non-positive and end the branching. There are four such sequences.

  • Total termination paths = 2 + 4 = 6. Each path returns q = 10, so the final result printed is 6 × 10 = 60.

Therefore the program prints 60.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir