Page 41 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 41
Fundamentals of Data Structures
Notes Example: Factorial of 5 = 5 × 4 × 3 × 2 × 1
= 120
1 #include<stdio.h>
2 #include<conio.h>
3
4 int factorial(int);
5
6 int factorial (int i)
7 {
8 int f;
9 if(i==1)
10 return 1;
11 else
12 f = i* factorial (i-1);
13 return f;
14 }
15
16 void main()
17 {
18 int x;
19 clrscr();
20 printf("Enter any number to calculate factorial :");
21 scanf("%d",&x);
22 printf("\nFactorial : %d", factorial (x));
23 getch();
24 }
The output is shown as below:
Source: http://rajkishor09.hubpages.com/hub/C-Programming-Recursive-Function
So from line no. 6 – 14 is a user defined recursive function “factorial” that calculates factorial of
any given number. This function accepts integer type argument/parameter and return integer
value.
In line no. 9 we are checking that whether value of i is equal to 1 or not; i is an integer variable
which contains value passed from main function i.e. value of integer variable x. If user enters 1
then the factorial of 1 will be 1. If user enters any value greater than 1 like 5 then it will execute
statement in line no. 12 to calculate factorial of 5. This line is extremely important because in this
line we implemented recursion logic.
34 LOVELY PROFESSIONAL UNIVERSITY