+ 15
How and Where to get more info on Java operators and learn the logic of this code. Please explain so I will
understand the logic coz it's confusing to me: Please help. 🙇🍣 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.print(f(4)); } }
4 odpowiedzi
+ 16
first its static function that's why we accessing it directly without object .when calling f(4) its passing argument 4 to
f(int x)
1 pass: x=4 not equal to 0 so return 1+ f(4-1)
in this above section its calling the function again that is what called as nesting of methods .
2 pass: x =3 not 0 so return 1+f(3-1)
3 pass: x= 2 not 0 so return 1+ f(2-1)
4 pass: x= 1 not 0 so return 1+ f(1-1)
5pass: x= 0 so its return 2
finally it return 1+1+1+1+2 =6
hope this help u :)
+ 6
It's a simple code, you have a class, and inside that class a method which receives an int as parameter, if that int (x) is zero, it returns two, else returns itself (executes the method again but with x-1) and then it adds one.
The main method just calls the method and prints its return.
+ 5
It's a "recursion function", you can search with that keyword to learn more.
+ 4
This is an example of recursive function in Java. A common technique to write code more easy to understand. More examples https://www.javatpoint.com/recursion-in-java