[Java] Cant understand this simple factorial example
EDIT: Solved! Thanks for the very quick help! It was giving me such a headache.
This is from: http://chortle.ccsu.edu/java5/Notes/chap17/ch17_11.html
import java.util.Scanner;
class Factorial { public static void main (String[] args ) { Scanner scan = new Scanner( System.in ); long N, fact = 1;
System.out.print( "Enter N: " );
N = scan.nextLong();
if ( N >= 0 )
{
while ( N > 1 )
{
fact = fact * N;
N = N - 1;
}
System.out.println( "factorial is " + fact );
}
else
{
System.out.println("N must be zero or greater");
}
} }
I understand everything up until the while statement. I understand how "fact" and "n" are used to do count down like a factorial, but how is the factorial totaled for the " System.out.println( "factorial is " + fact );".
If n = 3, then it would execute till n =1, but why wouldn't I need a line that tallied up the changes and then multiplied them together?
Posted May 29, 2016, 7:28 PM UTC · edited
1110