+ 3

BagJava

Please can who explain code below Why output 5? 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.print(f(3)); }

13th Dec 2017, 4:26 AM
Стрельбицкий Мирослав
Стрельбицкий Мирослав - avatar
2 Answers
+ 9
public static int f(int x) { if(x==0) return 2; else return 1 +f(x - 1); //it will recursively call until value of x=0 and return 2 } public static void main(String args[]) { System.out.print(f(3)); } explanation :- in this function f() is recursively call until x=0 return 1+f(2)// in first call when x=3 ,f(3)=1+f(2) return f(2)=1+f(1)//in second call when x=2 return f(1)=1+f(0)//in third call when x=1 return 2 //f(0)=2 when x=0 so we can say that finally the output is rerun like this return 1+1+1+2=5 so finally output become 5
13th Dec 2017, 5:15 AM
GAWEN STEASY
GAWEN STEASY - avatar