Program to Find Factorial of n using While loop
- Write a program to Find Factorial of n using While loop in C
- Write a program to Find Factorial of n using While loop in C++
- Write a program to Find Factorial of n using While loop in Python
- Write a program to Find Factorial of n using While loop in PHP
- Write a program to Find Factorial of n using While loop in Java
- Write a program to Find Factorial of n using While loop in Java Script
- Write a program to Find Factorial of n using While loop in C#
Explanation:
Using a for loop, you multiply each integer from 1 to n to obtain the factorial of a given number n. The definition of a number n’s factorial is:
The formula 𝑛! = 𝑛 × (𝑛 −1) × (𝑛 −2) × ⋯ × 1
(n−1) × (n−2) × ⋯ × 1 = n!
Logic
- Initialize a variable factorial to 1.
- Use a While loop to iterate through numbers from 1 to n.
- Multiply factorial by the current number in each iteration.
- Print the final value of factorial.
Program to Find Factorial of n using While loop
-
C
-
C++
-
Python
-
PHP
-
JAVA
-
Java Script
-
C#
#include <stdio.h>
int main() {
int n, fact = 1;
printf("Enter a number: ");
scanf("%d", &n);
while (n > 1) {
fact *= n;
n--;
}
printf("Factorial: %d\n", fact);
return 0;
}
#include <iostream>
using namespace std;
int main() {
int n, fact = 1;
cout << "Enter a number: ";
cin >> n;
while (n > 1) {
fact *= n;
n--;
}
cout << "Factorial: " << fact << endl;
return 0;
}
n = int(input("Enter a number: "))
fact = 1
while n > 1:
fact *= n
n -= 1
print(f"Factorial: {fact}")
<?php
$n = (int)readline("Enter a number: ");
$fact = 1;
while ($n > 1) {
$fact *= $n;
$n--;
}
echo "Factorial: $fact\n";
?>
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int fact = 1;
while (n > 1) {
fact *= n;
n--;
}
System.out.println("Factorial: " + fact);
sc.close();
}
}
let n = parseInt(prompt("Enter a number: "));
let fact = 1;
while (n > 1) {
fact *= n;
n--;
}
console.log(`Factorial: ${fact}`);
using System;
class Program {
static void Main() {
Console.Write("Enter a number: ");
int n = int.Parse(Console.ReadLine());
int fact = 1;
while (n > 1) {
fact *= n;
n--;
}
Console.WriteLine($"Factorial: {fact}");
}
}