Int testint x int y if x y return x else if x y return x

Int test(int x, int y) {if (x == y) return x; else if (x > y) return (x + y); else return test(x + 1, y - 1);} What is the output of the following statements? cout

Solution

//i have tested this code from main function

#include <iostream>

using namespace std;

int test(int x,int y){
if(x==y)
return x;
else if(x>y)
return (x+y);
else
return test(x+1,y-1);
}
int main()
{
  
cout <<test(5,10)<<endl;
cout <<test(3,19)<<endl;

return 0;
}

************OUTPUT**********
15
11
************OUTPUT**********

Explanation:test(5,10)
1.here x is not equal to y and x <y hence it will call recursive function test(x+1,y-1) i.e test(6,9)
2.it will call recursive function test(x+1,y-1) i.e test(7,8)
3.it will call recursive function test(x+1,y-1) i.e test(8,7)
4.Now x > y ,hence return(x+y),i.e 8+7=15,hence final output=15

Explanation:test(3,19)
1.here x is not equal to y and x <y hence it will call recursive function test(x+1,y-1) i.e test(4,18)
2.it will call recursive function test(x+1,y-1) i.e test(5,17)
3.it will call recursive function test(x+1,y-1) i.e test(6,16)
4.it will call recursive function test(x+1,y-1) i.e test(7,15)
5.it will call recursive function test(x+1,y-1) i.e test(8,14)
6.it will call recursive function test(x+1,y-1) i.e test(9,13)
7.it will call recursive function test(x+1,y-1) i.e test(10,12)
8.it will call recursive function test(x+1,y-1) i.e test(11,11)
9.Now x==y ,hence return x,i.e x=11,hence final output=11

Please let me know in case of any doubt,thanks.

 Int test(int x, int y) {if (x == y) return x; else if (x > y) return (x + y); else return test(x + 1, y - 1);} What is the output of the following statement

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site