Você está na página 1de 12

RECURSION

Any function which calls itself is called recursive. A recursive ethod solves a
problem by calling a coy of itself to work on a smaller problem
Example-Factorial problem n!=nX (n-1)!= nX (n-1) X (n-2) !
Here the factorial of n is resolved by calling the factorial function but a siler one
for (n-1).
But this will end once we reach 1 ie we donot further call factorial function.
Thus it is important that the recursion terminates at a certain stage or we will
end up in a infinite loop.
Why recursionCampared to iterative code recursion code is shorter and easier.But all recursive
problems can be solved through iteration (looping).
Not all roblems can be resolved through recursion the mai one being the
problem can be solved by reducing it to a simler version of itself.
Another disadvatnge of recursion is extra memory requirement , because each
time the function is called (by itself) a new copy of the function is loaded on the
RAM.
/* Program to calculate factorial through recursion
#include<stdio.h>
Int fact(int)

Void main()
{
Int n;
Printf(Enter an integer to calculate n! \n);
Scanf(%d,&n);
Printf(Factorial of n is %d,fact(n));
}
Int fact(int N)
{
Int result

If(N==1)
Return 1;
Else
Result= N*fact(N-1)
Return (Result);
}

Supose you enter a value of 5


Fact(5)
Result=5*Fact(4)
Now fact(4) is to be resolved and anew copy of fact function is created
Result=4*Fact(3)
Now fact(3) is to be resolved and anew copy of fact function is created
Result=3*Fact(2)
Now fact(2) is to be resolved and anew copy of fact function is created
Result=2*Fact(1)
Now fact(1) is to be resolved and anew copy of fact function is created
Return 1 goes to fact(2) because this is what called the fact(1) not main() or
fact(5)
This is vey important to understand , the return value oes to theparent function
which invoked the child function .
Now fact(2) can process result=2X1 and this is returned to fact(3)
Fact(3) returns 6 to fact (4) which returns 24 to fact(5) which returns 120 to
main.
Thus printf statement of the main will output the resut of fact(5) on the screen

Now suppose the problem is to find sum of first n natural nubers, how will the
program look like?

/* Program to calculate sum of first n natural numbers through recursion


#include<stdio.h>
Int sum(int)

Void main()
{
Int n;
Printf(Enter an integer to calculate sum of first n natural numbers \n);
Scanf(%d,&n);
Printf(Sum of first n natural numbers is %d,sum(n));
}
Int sum(int N)
{
Int result
If(N==1)
Return 1;
Else
Result= N+sum(N-1)
Return (Result);
}
The program is vey similar to factorial example discussed above
Next we will see a program which will print Fibonacci series using recursion.
Fibonacci series is 1 1 2 3 5 8 13 21 34 55 89 143.
First 2 numbers is 1 but rest of the series is sum of previous 2 numbes ie 2=1+1,
3=2+1, 5=3+289=55+34
Suppose we need to find 5th term of Fibonacci series written as Fib(5)
Fib(5)=Fib(4)+Fib(3)

But Fib(4)=Fib(3)+Fib(2)
Fib(3)=Fib(2)+Fib(1)
Now we know Fib(1) and Fib(2) are 1 so for solving
Fib(5) we convert it as
Fib(5)=Fib(4)+Fib(3)=Fib(3)+Fib(2) +
Fib(2)+Fib(1)=Fib(2)+Fib(1)+Fib(2)+Fib(2)+Fib(1)=
1+1+1+1+1=5, This logic can be implemented as a rogra to print the nth eleent
of the Fibonacci series
/* Program to print nth eleent of the Fibonacci series
#include<stdio.h>
Int Fib(Int)
Void main()
{
Int n;
Printf(Enter the element number of the Fibonacci series \n);
Scanf(%d,&n);
Printf(The elemt of Fibonacci series is %d \n,Fib(n));
}
Int Fib(int N)
{
If (N==1 || N==2)
Return 1;
Else
Result=Fib(N-1)+Fib(N-2);
Return (Result);
}
Supose n=7 , we need to calculate Fib(7)
By recursion Fib(7)=Fib(6)+Fib(5) ie 2 child functions are created in this case

Fib(6)=fib(5)+fib(4) and so on till everything is resolved in terms of Fib(2) and


fib(1) when 1 is returned.
Now if we need to printfirst n numbers of the Fibonacci series what will we do?
/* Program to print first n eleents of the Fibonacci series
#include<stdio.h>
Int Fib(Int)
Void main()
{
Int i;
Int n;
Printf(Enter the elements for the Fibonacci series \n);
Scanf(%d,&n);
For(i=1;i<=n,i++)
Printf( %d ,Fib(i));
}
Int Fib(int N)
{
If (N==1 || N==2)
Return 1;
Else
Result=Fib(N-1)+Fib(N-2);
Return (Result);
}
This will evaluate fib(i) for values i-1,2,3n and print the same on the screen.
Now we will see how to calculate the Greatest Common Divisor of two integers
through recursion
GCD of 2 numbers the largest nuber which divides both the nubers with 0 as
reminder
How to calculate GCD of 2 nubers say 75 and 125

Factors of 75 are 75,25,5,1


Factors of 125 are 125,25,5,1, same can be done by converting the number into
power of primes and taking the axiom coon power
Ir 75= 5^2X3^1
125=5^3
Thus common being 5^2
Thus GCD (75,125) is 25. This is quite easy for sall nubers but for large nubers
we can use Euclids thero which says that GCD (m,n)=GCD(m%n,n) if m>n or
GCD (m,n%m) if n>m.
Ie GCD (75,125)=GCD(75,50)=GCD(25,50)=25.
Thus we can convert a coplex proble into a sipler recursive proble.
/*Program for finding GCD of 2 nubers through recursion
/*Euclids thermo m GCD(m,n)=GCD (m%n,n) if m>n or GCD(m,n%m) if n>m.
#include<stdio.h>
Int GCD (int,int)
Void main()
{
Int m,n;
Printf(Enter 2 integers to calculate the GCD \n);
Scanf(%d %d,&m,&n);
Printf(The GCD is %d \n,GCD(m,n));
}
Int GCD(int M,int N)
{
If (M==N)
Return M;
If((M>N)&&(M%N==0))
Return N;
Elseif ((M>N)&&(M%N !=0))

Return GCD(M%N,N);
If((N>M)&&(N%M==0))
Return M;
Elseif ((N>M)&&(N%M !=0))
Return GCD(M,N%M);
}

Supose we enter 1571 ,62 as m and n respectively


Elseif ((M>N)&&(M%N !=0))
Return GCD(M%N,N);
Will recursively call GCD(59,62)
Which will recursively call GCD(59,3)
Which willcall GCD(2,3) which will recursively call GCD(2,1) which will recursively
call GCD(1,1) now the return will be 1.

pRogra to rint all binary nubrs of size 10


/*Progra m to print all binary numbers of size 0
#inclde<stdio.h>
Void main()
{
Char n[11];
n[10]=\0;
binarygen(n,10)
}

Now let us consider a rogram which will print all perutations of the string entered
by the user hrough recursion. Meaning if user enters the string ABC the rogra ust
output ABC,ACB , BAC, BCA ,CAB, CBA.
First let us see how the problem can be convered to recursive logic-

String,i=o to n where n is strlen-1


Levels n-1

In first level I have swapped the first eleent with the eleents after it (2 nd, 3 rd
etc)
In level 2 I have swaped the second elent with the eleent after it (3 rd,4th etc)
In level 3 I have swapped the third elemt with the eleent after it (4 th eleent)

AB
I0 n1 j0
AB

i1n1 AB

I0 n1 j0
AB
I0 n1 j1
BA i1n1 BA
I0 n1 j1
Ab

ABC

Then we will solve the Greatest common divisor GCD by recursion


Rinting all permutations of a given string
Generate all binary nubers
Power function which can handle negative values
Recursive function to print entered charaters in reverse orders
Recursive function to convert decial nmber into binary number.

Print all binary numbers of length n through recursion


Assume n=3 then we need
000 001 010 011 100 110 111

/* Program to print all binary nubers of length n using recursion


#include<stdio.h>
Void genbinary(int,char[]);

Void main()

{
Char A[4]
A[4]=\0;
Genbinary(3,A);
}
?

Void genbinary(int n ,char A[])

N=3

{
If(n<1)
0
pRintf(\n %s,A);

print

else
{
A[n-1]=0;

N=3

N=2

N=1

Genbinary(n-1,A);
A[n-1]=1;
Genbinary(n-1,A);
}
}

N=3

N=2

N=1

N=1

N=2

N=2

N=1

print

print

Você também pode gostar