Recursion
Recursion is a process of calling a function repeatedly until a certain condition is met.
Explanation of the program
This program takes as input, the number for which the factorial needs to be find, and stores it in the variable n. The variable f calls the fact() function, which takes as input the number n. The value returned from the fact() is stored if f, which is the factorial of the number.
The fact() function takes as input the number n, this function recursively calls itself until the value of its parameter equals to 1, each time decreasing the value of n.
Example
n=3
Below phases shows function call, condition check and return value respectively.
Phase 1
fact(3) 3 !=1 3*=fact(2)
Execution is paused since value for fact(2) is not available.
Phase 2
fact(2) 2!=1 2*=fact(1)
Execution is paused since value for fact(1) is not available.
Phase 3
fact(1) 1=1 return 1
going back to phase 2 with the value for fact(1)
2*=1 => a =2
going back to phase 1 with the value for fact(2)
3*=2 => a = 6
Factorial is 6
Program
//factorial program in c
#include<stdio.h> #include<conio.h> int fact(int n); void main() { clrscr(); int n,f; printf("Enter the number"); scanf("%d",&n); f=fact(n); printf("Factorial is %d",f); getch(); } int fact(int a) { if(a==1) return 1; else a*=fact(a-1); return(a); }
Output
C program to find the factorial of a number using recursion |
No comments:
Post a Comment