Вы находитесь на странице: 1из 9

# A Function may call itself again and again is called Recursive Function

Session Objectives
Define Recursive Functions Write a Program to find the factorial using Recursive Method

Factorial Function
Recursive definition of a process can also be explained with the help of a simple factorial example. 5 factorial (5!) is equal to 5 * 4 * 3 * 2 * 1 = 120 We can define this as follows -

This algorithm is called iterative because it calls for explicit repetition of some process until a certain condition is met. This algorithm can be translated readily into the C function that returns x!, where x is the input parameter.

Factorial Function
The following example depicts the actual process that needs to be carried out to calculate the factorial of a number using recursive functions

Recursion Summary
Commonly used programming languages like Fortran, Cobol and many machine level languages, do not allow recursive functions. If we know that the recursive solution is correct and we have established techniques for converting a recursive solution to a non-recursive one, we can create a correct solution in a non- recursive language. It is not uncommon for a programmer to be able to state a recursive solution for a problem.

Write a program to find the factorial of a given number using recursive method #include<stdio.h> #include<conio.h> void main() { int factorial(int); int n,d; clrscr(); printf("enter the number:"); scanf("%d",&n); d=factorial(n); printf("\n\n %d!=%d\n",n,d); getch(); } int factorial(int num) { if(num>1) return(num*factorial(num-1)); else return(1); }

## Enter the number :5 The factorial Result : 120

/* Fibonacci Series with Recursive Functions */ #include<stdio.h> int fib(int n) { int x,y; if(n<=1) return n; else x=fib(n-1); y=fib(n-2); return(x+y); } void main() { int n,num; printf("\n Enter the N Value"); scanf("%d",&n); num=fib(n); printf("\n The Number at %dth Position is %d in fibonacci series",n,num); }

To multiply two numbers Using Recursive Method #include<stdio.h> #include<conio.h> mul(int a,int b) { if(b==1) return a; else return(mul(a,b-1)+a); } void main() { int a,b,result=0; clrscr(); printf("\n Enter a and b values"); scanf("%d %d",&a,&b); result=mul(a,b); printf("\n The multiplication is = %d ,result); getch(); }

Session Summary
Recursion is a process by which a function calls itself repeatedly until some specified condition has been satisfied. The function name in the function call and the function definition should be the same

## The called function returns only one value per call

Function definition may appear in any order (i.e., before or after the main() function)

EXERCISES
1. Write a program to find the NCR factorial of a given number?

2. Write a program to search an element using binary search method using Recursive
method? 3. Write a program to find the square of first N Numbers and to calculate its sum?