Factorial of a Number

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 35:- Factorial of a Number

To calculate the factorial of a given number in Java, you can use a loop to multiply the number with its preceding integers until you reach 1. The factorial of a non-negative integer n is denoted by n! and is the product of all positive integers from 1 to n. Here's a Java program to calculate the factorial of a given number:

javaCopy code

import java.util.Scanner; public class Factorial {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        System.out.print("Enter a non-negative integer: ");        int number = scanner.nextInt();        if (number < 0) {            System.out.println("Factorial is not defined for negative numbers.");        } else {            long factorial = 1; // Use long to handle large factorials            for (int i = 1; i <= number; i++) {                factorial *= i;            }            System.out.println("Factorial of " + number + " is: " + factorial);        }        scanner.close();    } }

Example output:

mathematicaCopy code

Enter a non-negative integer: 5 Factorial of 5 is: 120

In the program above, we take the user input for the number and store it in the variable number. We use a for loop to calculate the factorial of the number by multiplying factorial with integers from 1 to number. The result is stored in the factorial variable. If the user enters a negative number, we print a message stating that the factorial is not defined for negative numbers.

Note: The factorial of large numbers can grow very quickly and may exceed the range of int or long data types. To handle large factorials, you can use BigInteger class from the java.math package, which allows working with arbitrarily large integers. However, for most practical purposes, using long should be sufficient.

6. Loops

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?