Program to find Factorial of a Number
Following is the program to find factorial of a number using
for
loop.#include<stdio.h> #include<conio.h> void main() { int fact,i,n; fact = 1; printf("Enter the number\t"); scanf("%d" , &n); for(i = 1; i <= n; i++) { fact = fact*i; } printf("Factorial of %d is %d", n , fact); getch(); }
Output
Enter the number 5 Factorial of 5 is 120
Program to find Factorial of a Number using Recursion
In this program we will not use for loop, but we will find the factorial using recursion.
#include<stdio.h> #include<conio.h> int factorial(int n); void main() { int fact, i, n; printf("Enter the number\t"); scanf("%d", &n); fact = factorial(n); printf("Factorial of %d is %d", n, fact); getch(); } int factorial(int n) { int fact = 1; if(n==1) { return fact; } else { fact = n * factorial(n-1); return fact; } }
Output
Enter the number 5 Factorial of 5 is 120
No comments:
Post a Comment