IP-14.c (1231B)
1 /* Write a program to calculate the factorial of a number 2 (i) using recursion 3 (ii) using iteration 4 */ 5 6 #include <stdio.h> 7 8 long long int fact_tail_rec(int, long long int); 9 long long int fact_rec(int); 10 long long int fact_ite(int); 11 12 int main() 13 { 14 int n; 15 printf("Enter the number: "); 16 scanf("%d", &n); 17 if (n < 0) 18 { 19 printf("\nFactorial of negetive number is not possible."); 20 return 1; 21 } 22 printf("\nFactorial of %d (Tail-Recursion) = %lld", n, fact_tail_rec(n, 1)); 23 printf("\nFactorial of %d (Recursion) = %lld", n, fact_rec(n)); 24 printf("\nFactorial of %d (Iteration) = %lld", n, fact_ite(n)); 25 return 0; 26 } 27 28 long long int fact_tail_rec(int n, long long int result) 29 { 30 if (n == 0 || n == 1) 31 { 32 return result; 33 } 34 else 35 { 36 return fact_tail_rec(n - 1, n * result); 37 } 38 } 39 40 long long int fact_rec(int n) 41 { 42 if (n == 0 || n == 1) 43 { 44 return 1; 45 } 46 else 47 { 48 return n * fact_rec(n - 1); 49 } 50 } 51 52 long long int fact_ite(int n) 53 { 54 int i; 55 long long int result = 1; 56 if (n == 0 || n == 1) 57 { 58 return 1; 59 } 60 for (i = 2; i <= n; i++) 61 { 62 result *= i; 63 } 64 return result; 65 }