0

Could someone explain this code?

public class Main { public static void main(String[] args) { System.out.println(tri(3)); } static int tri(int n){ return n==0?0:n==1?1:tri(n-1)+tri(n-2); } }

29th Oct 2022, 12:47 PM
Killiam Chances
Killiam Chances - avatar
2 odpowiedzi
+ 3
You are calling tri(3 ) method with passing value 3. The ternary conditional statement: condition ? (True) :( False) works like if condition is true then True block is executed else False block executed. so if n == 0 then it returns 0 else goes to false part, it has again ternary condition nested. So that works same way as if n==1 then it returns 1 else executes tri( n -1 ) + tri( n-2 ) . call the self method in recursive passion. So tri(3) => tri(2) + tri(1) Here both calls are new independent calls pushed into stack so tri(2) => tri(1) + tri(0) => 1+0 = 1 And tri(1) => 1 So tri(3) => tri(2) + tri(1) => 1+1 =2 Finally returns 2 edit: for clearence, simplipy it by : public class Main { public static void main(String[] args) { System.out.println(tri(3)); } static int tri(int n){ return n<=1? n : tri(n-1)+tri(n-2); } }
29th Oct 2022, 1:06 PM
Jayakrishna 🇮🇳
0
System.out.println( tri(3, 0) ); } static int tri(int n, int level){ System.out.println( n +", level=" +level); return n==0? 0: n==1? 1: tri(n-1, level+1) +tri(n-2, level+1); }
30th Oct 2022, 8:32 PM
zemiak