Calculating factorials in Java and printing the steps -


the following java code calculates factorial of given number , prints intermediate steps.

public class factorial {    public static int getfactorial(int number) {      int n = number;      int factorial = 1;       while(n > 1) {        factorial *= n;        n--;         system.out.println(factorial + " * " + n + " = " + factorial);      }      return factorial;    } } 

when method called:

factorial.getfactorial(4); 

should print console following:

4 * 3 = 12 12 * 2 = 24 24 * 1 = 24 

but instead prints following:

4 * 3 = 4 12 * 2 = 12 24 * 1 = 24 

what doing wrong?

that happening because you're printing factorial variable only. replace:

system.out.println(factorial + " * " + n + " = " + factorial); 

with:

system.out.println(factorial + " * " + n + " = " + factorial * n); 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -