Java How do I output the initial value of a method's variable before it enters the first recursion of the method? -


any idea on how print initial variable used in classic factorial recursion? here's 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 output looks this:

n:24 output:24 answer:24 

but i'm trying have show n before enters second iteration of factorial method. n should showing 4, not 24. in advance.

you need change line:

system.out.println("output:" + factorial(initialn(4)));  

you should call initialn() inside factorial because methods executed within , outward.

as side note, write this:

public static int factorial3(int num){  if(num == 0)   return 1; else{   if(i==0) \\ global variable initialized 0    system.out.println("n:" + num);   i++;   return num * factorial3(num-1);   } } 

and call this:

system.out.println(factorial3(4)); 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -