Vikki Nayyar :
In this program, if the user enters the number 3, the o/p will be 3 2 1 1 2 3 , I understood how 3 2 1 came, but I didn't understand how 1 2 3 came at the end.
class GFG{
static void printFun(int test)
{
if (test < 1)
return;
else
{
System.out.printf("%d ",test);
printFun(test-1); // statement 2
System.out.printf("%d ",test);
return;
}
}
public static void main(String[] args)
{
int test = 3;
printFun(test);
}
}
Sweeper :
One way to trace through recursive functions is by expanding every recursive call, like a math expression.
First we start with
printFun(3)
That expands to:
print(3) // I have shortened System.out.printf here to just "print" to remove the noise
printFun(2)
print(3)
We still have a recursive call (printFun(2)
), so let's expand that.
print(3)
print(2)
printFun(1)
print(2)
print(3)
Continue expanding:
print(3)
print(2)
print(1)
printFun(0)
print(1)
print(2)
print(3)
And one last time (since printFun(0)
doesn't do anything, we just remove it):
print(3)
print(2)
print(1)
print(1)
print(2)
print(3)
Oh look! That will produce the output 3 2 1 1 2 3
!