Reputation: 1199
Any idea on how to print the initial variable used in the classic factorial recursion? Here's what I have.
public class factorial{
public static void main(String[] args){
System.out.println("Output:" + initialN(factorial(4)));
System.out.println("Answer:24");
}
public static int factorial(int n){
if(n == 1){
return 1;
}
else{
return n*(n-1);
}
}
public static int initialN(int n){
int init = n;
System.out.println("N:" + init); return init;
}
}
Right now my output looks like this:
N:24
Output:24
Answer:24
But I'm trying to have it show only what n is initially before it enters the second iteration of the factorial method. So N should be showing as 4, not 24. Thanks in advance.
Upvotes: 0
Views: 141
Reputation: 162
You just need to change this line:
System.out.println("Output:" + factorial(initialN(4)));
You should call initialN()
inside factorial because the methods are executed from within and then outward.
As a side note, I would write it like this:
public static int factorial3(int num){
if(num == 0)
return 1;
else{
if(i==0) \\ i is global variable initialized to zero
System.out.println("N:" + num);
i++;
return num * factorial3(num-1);
}
}
and call it like this:
System.out.println(factorial3(4));
Upvotes: 3
Reputation: 1199
I got it. If you call the recursion method from a another method, you can print the initial variable. here is my solution. I'd be interested to see if anyone has a more simple solution.
public class factorial{
public static void main(String[] args){
System.out.println("Output:" + (factorial(3))); System.out.println("Answer:6");
System.out.println("Output:" + (factorial(4))); System.out.println("Answer:24");
System.out.print("--------------------");
}
public static int factorial(int n){
System.out.println("--------------------\nN:" + n);
return factorial2(n);
}
public static int factorial2(int n){
if(n == 1){
return 1;
}
else{
return n*factorial2(n-1);
}
}
}
Upvotes: 0