I am having trouble understanding recursion. I understand the theory. Like when a function calls itself, needs a base case to end the recursion and all that but when it comes to using it in a program, I get really confused. For example, I have posted some code below. When I call print function before the recursive function..it prints the numbers in reverse order (54321) and when I call it after the recursion, it prints it as 12345. Why is that?
public class Main {
public static void main(String[] args) {
printNumbers(5);
}
public static void printNumbers(int num){
if(num==0) {
return;
}
System.out.println(num); // this prints 54321
printNumbers(num-1);
System.out.println(num);//this prints 12345
}
}
printNumbersit will return to the place it was called from, meaning that you get the numbers in reverse order from the way they were pushed - MadProgrammer