Write a program to find the factorial of a given number using recursion
Example:
Input: n = 5 Output: Factorial is 120
Approach
C
#include <stdio.h>int factRec(int n){if (n <= 1)return 1;return n * factRec(n - 1);}int main(){int n;printf("Enter a number: ");scanf("%d", &n);int fact = factRec(n);printf("Factorial is %d", fact);return 0;}
Java
import java.util.Scanner;public class Main{public static void main(String[] args) {System.out.println("enter the number");Scanner sc = new Scanner(System.in);int num = sc.nextInt();System.out.println("factorial of "+ num+" is "+factRec(num)) ;}public static int factRec(int n){if (n <= 1)return 1;return n * factRec(n - 1);}}
No comments:
Post a Comment