Write a program to calculate the factorial of a given number using the function
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 "+fact(num));}public static int fact(int num){if(num<=1){return 1;}else{return num* fact(num-1);}}}
No comments:
Post a Comment