Tutorials Java Calculating factorial of number in Java

Calculating factorial of number in Java

This example below accepts number from user and calculates factorial using while loop and prints it.

import java.util.Scanner;

public class Factorial {

	public static void main(String[] args) {
		int number;
                int factorial = 1;

		Scanner input = new Scanner(System.in);

		//accept input from user
		System.out.println("Enter A Number :");
		number = input.nextInt();

		int i = 1;

		// while loops
		while (i <= number) {
			factorial = factorial * i;
			i++;
		}

		System.out.println("Factorial is = " + factorial);
	}
}

Output

Enter A Number :
6
Factorial is = 720
Total
0
Shares
guest
0 Comments
Inline Feedbacks
View all comments
Previous Post
Java Tutorials

Drawing a pyramid using loops in Java

Next Post

How to Start One Activity From Another in Xamarin Android

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
0
Would love your thoughts, please comment.x
()
x