in Programming in C retagged by
398 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
in Programming in C retagged by
398 views

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.

3 Comments

Suppose x > y, we will repetitively decrease x by y. Three cases are possible.

Case 1: We reach the stage where x < y.

In this case, “if” condition will never be true and x gets no chance to become zero and infinite loop/recursion happens.

Case 2: x = y. In this case, “else” block runs and y = y -x =  0.

In this case, x will remain whatever it is currently and would get no chance to become zero and infinite loop/recursion happens.

Case 3: 2*y > x > y.

In this case, x = x – y and now, x < y and we go back to case 1.

Hence, we can conclude that infinite loop/recursion is inevitable unless x = 0 is passed originally.

 

1
1

if (x > = y)

this equal is needed to stop the infinite recursion.

2
2

Or we can add a condition if(y==0)

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

0 votes
0 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.

Answer:

Related questions