Program to calculate Factorial of a Number

Description

Factorial of a number n is represented as n!.
The factorial of n = 1 x 2 x 3 x....x n
Note:
1) Factorial of negative number cannot be calculated.
2) Factorial of 0 is 1.

C/C++

/* C Program to calculate Factorial of a Number */
//Save it as Factorial.c

#include<stdio.h>
int main(){

    int i, num, fact=1;

    printf("Enter a number : ");
    scanf("%d",&num);

    if(num<0){
        printf("Factorial cannot be calculated");
    }else if(num == 1){
        printf("Factorial of 1 is 1");
    }else{
        for(i=1;i<=num;i++){
            fact *= i;
        }
        printf("Factorial of %d is %d",num,fact);
    }

    return 0;
}
Input:
Enter a number : 6

Output:
Factorial of 6 is 720

Java

/* Java Program to calculate Factorial of a Number */
//Save it as Factorial.java

import java.io.*;
import java.util.Scanner;

public class Factorial {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        
        int i, num, fact=1;

        System.out.println("Enter a number : ");
        num = scanner.nextInt();

        if(num<0){
            System.out.println("Factorial cannot be calculated");
        }else if(num == 1){
            System.out.println("Factorial of 1 is 1");
        }else{
            for(i=1;i<=num;i++){
                fact *= i;
            }
            System.out.println("Factorial of "+num+" is "+fact);
        }
    }
}
Input:
Enter a number : 
6

Output:
Factorial of 6 is 720

Related Programs

1) Program to calculate factorial using Recursion
2) Program to find factors of a Number
3) Program to find modulus of two numbers
4) Program to reverse a number
5) Program to find LCM(Least Common Multiple)
6) Program to find largest and smallest digit in a Number
7) Program to find largest and smallest character in a String
8) Program to add two complex numbers
9) Program to calculate volume and surface area of cylinder
10) Check whether a given number is a perfect number or not
Share Me

Leave a Reply