Question:
How to print out a factorial.
8! should print out:
1, 2, 6, 24, 120, 720, 5040, 40320.
8! should print out:
1, 2, 6, 24, 120, 720, 5040, 40320.
Code:
import java.util.*; public class Factorial { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Please enter a number: "); int number = sc.nextInt(); System.out.print("1"); for(int i=2;i<=number;i++){ System.out.print( ", " + fact(i)); } System.out.println("."); } static int fact(int b) { if(b <= 1) { return 1; } else { return b * fact(b-1); } } }
Output:
$ java Factorial Please enter a number: 8 1, 2, 6, 24, 120, 720, 5040, 40320.