retagged by
423 views
6 votes
6 votes

What will be the output of the following program?

#include<stdio.h> 
int rec(int x, int y) {
static int count = 0;
if (x == 0)
  return count;
count++;
if (x > y)
  rec(x - y, y);
else
  rec(x, y - x);
return count;
}
main() {
    int i = 10, j = 2, n;
    n = rec(i, j);
    printf("%d", n);
}

  1. $4$
  2. $5$
  3. $6$
  4. Infinite loop
retagged by

3 Answers

2 votes
2 votes

int rec(int x, int y) → this function returns some value only when x = 0;

Now, when we pass non-zero x, will x parameter for any future call ever become 0?

We’re recursively calling rec, in only one case we’re modifying parameter x, only when x > y, and that to x – y.

Now, this x – y can never become 0.

Therefore, rec(x, y) for all non-zero x, will result in infinite recursive calls.

Answer :- D.

1 votes
1 votes

The function terminates only when x = 0 

but here when it is rec(2,0) => x > y and again rec(x-y, y) = rec(2-0,0) = rec(2,0) executes and this function keeps on repeating and it gets stackoverflow.

0 votes
0 votes

Answer:D

The given program calculates the greatest common divisor (GCD) of two integers x and y using recursion. However, it lacks a termination condition for when x and y are equal, leading to an infinite loop. Consequently, the program will not produce any output and will continue executing indefinitely.

Answer:

Related questions