JavaScript Code to Calculate Factorial of any number

Factorial of a number, is the product of all positive integer number less or equal than that given number.

factorialnumber


Factorial of a Number

Factorial of a number, is the product of all positive integer number less or equal than that given number.

Example: Factorial of 5 is 5 × 4 × 3 × 2 × 1 = 120 and is denoted by 5!.


Factorial in JavaScript

JavaScript code will take any number by using the prompt command and then perform the logic.

  • The factorial of a negative number doesn't exist.

  • The factorial of zero and one is one.

  • The factorial of any other positive number is obtained by performing a for loop in JavaScript.


JavaScript Code to Find Factorial

<HTML> <HEAD> <TITLE>Factorial of any given number</TITLE> <SCRIPT> LET n = parseInt(prompt('Enter a positive integer: ')); if (n < 0) { alert("Factorial for negative number does not exist"); } else if (n == 0 || n == 1) { alert("The Factorial is 1"); } else { let fact = 1; for (i = 1; i <= n; i++) { fact *= i; } alert(`The factorial is ${fact}`); } </SCRIPT> </HEAD> <BODY> </BODY> </HTML>

How It Works

  1. The program prompts the user to enter a positive integer.

  2. It checks if the number is negative, zero, or one and gives the appropriate response.

  3. For other positive integers, a for loop multiplies all integers from 1 up to the number to calculate the factorial.

  4. The result is displayed using an alert box.


Conclusion

Calculating factorials is a fundamental concept in mathematics and programming. Using JavaScript, we can efficiently compute factorials for positive integers, making it easy to integrate into web-based applications or learning exercises. Understanding loops and conditional statements through this example strengthens core programming skills.

How to connect PHP and MYSQL ?

Previous Post Next Post