When I run this function by inputting 2 and I do not understand why it returns 83 and not 5 since it should call function(1) in the else statement and then the if statement should get executed and the function should return 5.
public static int function(int y) {
if (y == 1)
return 5;
function(y - 1);
y = y 1;
return 83;
}
CodePudding user response:
It returns 83 because you are not using the return value of function(y - 1);
To test it try:
public static int function(int y) {
if (y == 1)
return 5;
else {
int returnedValue = function(y - 1);
System.out.println("un used returned value: " returnedValue);
y = y 1;
return 83;
}
}
Change to:
public static int function(int y) {
if (y == 1) return 5;
/*else*/
return function(y - 1);
}
CodePudding user response:
With input: y = 2,
else condition will be handled.
function(y - 1);//nothing impact to y
y = y 1;// y =3
return 83; // but finally return 83
Do you get the point?
CodePudding user response:
Since you do not return function(y-1)
, the statement is as good as making the function void (for that call).
So, as soon as the control reaches function(y-1) and eventually leads to calling function(1), you do get 5 but it is not returned to the driver function. What is instead returned is the value 83.
CodePudding user response:
Check this out:
public static int function(int y) {
if (y == 1)
return 5;
function(y - 1); // you do not use return value
y = y 1;
return 83; // you always get this return
}
It means that you can replace your function with:
public static int function(int y) {
return 83;
}
Looks like you want to do smth. like this:
public static int function(int y) {
return y == 1 ? 5 : function(y - 1);
}
but be careful, because for y < 1
you will have an infinite recursion (StackOverflowError
).