350 Programming and Data Structures
10.35 Write a program to calculate the factorial of an entered number by using a
recursive function.
# include <stdio.h>
# include <conio.h>
void main()
{
int x,f,fact(int)j
clrscr();
printf ("n Enter a Number
scanf ("%d",&x);
f=fdct(x);
printf ("n Factorial of %d is %d",x,f);
fact( m)
i
in tf=l;
if ( m ~ l )
retum(l);
else
f=m*fact(m -l);
return (f);
}
o i n m L
Enter a Number : 5
Factorial of 5 is 120
Explanation In this program a number is entered whose factorial is to be calculated. The entered
number is passed through the function f act (). The value of x is copied into m. If the entered
number is 1 the if condition is satisfied and 1 is returned through the first return statement. With
this value of x, recursion does not take place.
When the entered number is greater than 1, function fact () is called recursively. Each time the
value of m is multiplied with the decremented value of m in the statement f=m*fact (m-1). To
understand the recursive call of function f ac t () , execute the program in step mode (F7).
SU M M ARY
This chapter is focused on functions. You have studied how to initialize and use functions while
writing programs in C. How the functions interact with one another is also explained with examples.
It is also described how to use a function as an argument. The reader should know that a function
always returns integer value. Executing programs as illustrated in this chapter can demonstrate
this. Besides, a non-integer value can also be returned by specifying a data type in the function
prototype. The recursive nature of functions is also explained with suitable examples.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.37.10