In this example, we're going to be discussing how to calculate the factorial of a number using different programming languages. The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, the factorial of 5 (denoted as 5!) is 5 * 4 * 3 * 2 * 1 = 120.
#include <stdio.h>
int main() {
int num, i;
unsigned long long factorial = 1;
printf("Enter a number: ");
scanf("%d", &num);
// Check if the number is negative, positive, or zero
if (num < 0)
printf("Factorial of a negative number doesn't exist.");
else {
for (i = 1; i <= num; ++i) {
factorial *= i;
}
printf("Factorial of %d = %llu", num, factorial);
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int num, i;
unsigned long long factorial = 1;
cout << "Enter a number: ";
cin >> num;
// Check if the number is negative, positive, or zero
if (num < 0)
cout << "Factorial of a negative number doesn't exist.";
else {
for (i = 1; i <= num; ++i) {
factorial *= i;
}
cout << "Factorial of " << num << " = " << factorial;
}
return 0;
}
def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num - 1)
num = int(input("Enter a number: "))
print("Factorial of", num, "=", factorial(num))
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
long factorial = 1;
// Calculate factorial
for (int i = 1; i <= num; ++i) {
factorial *= i;
}
System.out.println("Factorial of " + num + " = " + factorial);
}
}