+ 15

Please help me explain this???

public class Program { public static int f(int x){ if (x==0) return 2; else return 1 + f(x-1); } public static void main(String[] args) { System.out.println(f(3)); } } // answer is 5

18th Oct 2017, 6:51 PM
Okoye Kenneth Collins
Okoye Kenneth Collins - avatar
8 Réponses
+ 17
OK thanks I get it now very helpful......however i still think in the adding backwards this section: x=2, 1+3=4 should be x=2, 1+2=3 because 1 + f(x-1) = 1 + f(2- 1) => 1 + 2(1) =>. 1+2=3... what do you think
19th Oct 2017, 12:50 AM
Okoye Kenneth Collins
Okoye Kenneth Collins - avatar
+ 14
still don't get it
18th Oct 2017, 7:08 PM
Okoye Kenneth Collins
Okoye Kenneth Collins - avatar
+ 14
" we have a base case and add backwards........"
18th Oct 2017, 7:10 PM
Okoye Kenneth Collins
Okoye Kenneth Collins - avatar
+ 3
The above program is the program of Recursion now in given program you had passed value 3 to function 'f' so from main method(system.out.print) calls goes to function 'f' in first iteration value of x is 3 so if(x==0) gets false and it goes to else part now actual implementation starts... just remember one key point related to return is (( Return is transfer control statement which returns the value to its caller only (caller may be anything main, function anything keep this point in mind and read below description) for Better understanding i maintain the operation number like 1,2,3... ## 1) else 1 + f(x-1) --> transfer value (2) to itself(recursion) ## 2) again if(x==0) gets false bcoz x=2 so it goes to else part else 1 + f(x-1) --> transfer value (1) to itself(recursion) ## 3) again if(x==0) gets false bcoz x=1 so it goes to else part else 1 + f(x-1) --> transfer value (0) to itself(recursion) ## 4) this time if(x==0) gets results true bcoz x=0 so it goes to statement present in if block which is 'return 2' now caller for --> (## 4) ) is (## 3) ) so return value 2 goes to (## 3) ) stage ## 5) so in this (## 3) ) we got value for expression f(x-1) i.e 2 so we implement statement present in else part i.e 2+1 = 3 now caller for --> (## 3) ) is (## 2) ) so return value 3 goes to (## 2) ) stage ## 6) so in this (## 2) ) we got value for expression f(x-1) i.e 3 so we implement statement present in else part i.e 3+1 = 4 now caller for --> (## 2) ) is (## 1) ) so return value 4 goes to (## 1) ) stage ## 7) so in this (## 1) ) we got value for expression f(x-1) i.e 4 so we implement statement present in else part i.e 4+1 = 5 now caller for --> (## 1) ) is in main() method i.e System.out.print(); so return value 4 goes to System.out.print(); and finally it prints 5 as output... thank you:) may this explanation helps for understanding concept of Recursion
23rd Oct 2017, 6:03 PM
Pranit Gandhi
Pranit Gandhi - avatar