Program to calculate factorial using Recursion

Description

Factorial of a non-negative integer, is multiplication of all integers smaller
than or equal to that integer. 
In recursion, there is a base condition. call method for calculating factorial
until it reaches to base condition

C/C++

/* C Program to calculate factorial using Recursion */
//Save it as FactorialUsingRecursion.c

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

    int num;

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

    int factorial = fact(num);

    printf("Factorial of %d is %d", num, factorial);

    return 0;
}

//Function to calculate factorial
int fact(int num){

    if(num == 1 || num == 0){
        return 1;
    }

    return num*fact(num-1);
}
Input:
Enter a non-negative number : 5

Output:
Factorial of 5 is 120

Java

/* Java Program to calculate factorial using Recursion */
//Save it as FactorialUsingRecursion.java

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

public class FactorialUsingRecursion {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter a non-negative number : ");
        int num = scanner.nextInt();
        
        
        int factorial = fact(num);
        
        System.out.println("Factorial of "+num+" is "+factorial);
    }
    
        //Function to calculate factorial
    private static int fact(int num) {
        
        if(num == 0 || num ==1) {
            return 1;
        }
        return num*fact(num-1);
    }
}
Input:
Enter a non-negative number : 
5

Output:
Factorial of 5 is 120

Related Programs

1) Program to calculate power of a number
2) Program to calculate power of a number using recursion
3) Program to Display Fibonacci Series using Recursion
4) Program to find HCF using Recursion
5) Program to find sum of digits of a number
6) Program to reverse a number
7) Program to convert Binary to Decimal
8) Program to convert Octal to Decimal
9) Program to calculate square root of a number without using standard library function sqrt()
10) Program to find HCF(Highest Common Factor)/GCD(Greatest Common Divisor) and LCM(Least Common Multiple)
Share Me

Leave a Reply