Lecture 2
Lecture 2
Lecture-2
Recursion
Recursion is deceptively simple in statement but exceptionally
complicated in implementation. Recursive procedures work fine in many
problems. Many programmers prefer recursion through simpler
alternatives are available. It is because recursion is elegant to use
through it is costly in terms of time and space. But using it is one thing
and getting involved with it is another.
Introduction to Recursion:
A function is recursive if a statement in the body of the function calls itself. Recursion is
the process of defining something in terms of itself. For a computer language to be
recursive, a function must be able to call itself.
For example, let us consider the function factr() shown below, which computers the
factorial of an integer.
#include <stdio.h>
int factorial (int);
main()
{
int num, fact;
printf (“Enter a positive integer value: ");
scanf (“%d”, &num);
fact = factorial (num);
printf ("\n Factorial of %d =%5d\n", num, fact);
}
return (result);
}
factorial (int n)
{
int i, result = 1;
if (n == 0)
Lecture Notes 13
Lecture Notes: Golam Moktader Daiyan, Assistant Prof., East Delta University
return (result);
else
{
for (i=1; i<=n; i++)
result = result * i;
}
return (result);
}
The operation of the non-recursive version is clear as it uses a loop starting at 1 and
ending at the target value and progressively multiplies each number by the moving
product.
When a function calls itself, new local variables and parameters are allocated storage
on the stack and the function code is executed with these new variables from the start.
A recursive call does not make a new copy of the function. Only the arguments and
variables are new. As each recursive call returns, the old local variables and
parameters are removed from the stack and execution resumes at the point of the
function call inside the function.
When writing recursive functions, you must have a exit condition somewhere to force
the function to return without the recursive call being executed. If you do not have an
exit condition, the recursive function will recurse forever until you run out of stack
space and indicate error about lack of memory, or stack overflow.
Iteration Recursion
Iteration explicitly user a repetition Recursion achieves repetition through
structure. repeated function calls.
Iteration terminates when the loop Recursion terminates when a base case
continuation. is recognized.
Iteration keeps modifying the counter Recursion keeps producing simple
until the loop continuation condition versions of the original problem until
fails. the base case is reached.
Iteration normally occurs within a loop Recursion causes another copy of the
so the extra memory assigned is function and hence a considerable
omitted. memory space’s occupied.
It reduces the processor’s operating It increases the processor’s operating
time. time.
Start out with some natural number N (in our example, 5). The recursive definition is:
n = 0, 0 ! = 1 Base Case
n > 0, n ! = n * (n - 1) ! Recursive Case
Lecture Notes 14
Lecture Notes: Golam Moktader Daiyan, Assistant Prof., East Delta University
Recursion Factorials:
5! =5 * 4! = 5 * = factr(5) = 5 * factr(4) =
4! = 4 *3! = 4 * = factr(4) = 4 * factr(3) =
3! = 3 * 2! = 3 * = factr(3) = 3 * factr(2) =
2! = 2 * 1! = 2 * = factr(2) = 2 * factr(1) =
1! = 1 * 0! = 1 * = factr(1) = 1 * factr(0) =
0! = 1 factr(0) =
We define 0! to equal 1, and we define factorial N (where N > 0), to be N * factorial (N-
1). All recursive functions must have an exit condition, that is a state when it does not
recurse upon itself. Our exit condition in this example is when N = 0.
When the factorial function is first called with, say, N = 5, here is what happens:
FUNCTION:
Does N = 0? No
Function Return Value = 5 * factorial (4)
FUNCTION:
Does N = 0? No
Function Return Value = 4 * factorial (3)
FUNCTION:
Does N = 0? No
Function Return Value = 3 * factorial (2)
FUNCTION:
Does N = 0? No
Function Return Value = 2 * factorial (1)
FUNCTION:
Does N = 0? No
Function Return Value = 1 * factorial (0)
FUNCTION:
Does N = 0? Yes
Function Return Value = 1
Lecture Notes 15
Lecture Notes: Golam Moktader Daiyan, Assistant Prof., East Delta University
Now, we have to trace our way back up! See, the factorial function was called six
times. At any function level call, all function level calls above still exist! So, when we
have N = 2, the function instances where N = 3, 4, and 5 are still waiting for their
return values.
So, the function call where N = 1 gets retraced first, once the final call returns 0. So,
the function call where N = 1 returns 1*1, or 1. The next higher function call, where N
= 2, returns 2 * 1 (1, because that's what the function call where N = 1 returned). You
just keep working up the chain.
And since N = 5 was the first function call (hence the last one to be recalled), the value
120 is returned.
In the game of Towers of Hanoi, there are three towers labeled 1, 2, and 3. The game
starts with n disks on tower A. For simplicity, let n is 3. The disks are numbered from 1
to 3, and without loss of generality we may assume that the diameter of each disk is
the same as its number. That is, disk 1 has diameter 1 (in some unit of measure), disk
2 has diameter 2, and disk 3 has diameter 3. All three disks start on tower A in the
order 1, 2, 3. The objective of the game is to move all the disks in tower 1 to entire
tower 3 using tower 2. That is, at no time can a larger disk be placed on a smaller disk.
Figure 3.11.1, illustrates the initial setup of towers of Hanoi. The figure 3.11.2,
illustrates the final setup of towers of Hanoi.
The rules to be followed in moving the disks from tower 1 tower 3 using tower 2 are as
follows:
To w er 1To w er 2To w er 3
Fig. 3. 1 1. 1. In it ia l s et u p of T o w ers of Ha n o i
Lecture Notes 16
Lecture Notes: Golam Moktader Daiyan, Assistant Prof., East Delta University
To w er 1To w er 2To w er 3
Fig 3. 1 1. 2. F in a l s et u p of T o w ers of Ha n o i
The towers of Hanoi problem can be easily implemented using recursion. To move the
largest disk to the bottom of tower 3, we move the remaining n – 1 disks to tower 2
and then move the largest disk to tower 3. Now we have the remaining n – 1 disks to
be moved to tower 3. This can be achieved by using the remaining two towers. We can
also use tower 3 to place any disk on it, since the disk placed on tower 3 is the largest
disk and continue the same operation to place the entire disks in tower 3 in order.
The program that uses recursion to produce a list of moves that shows how to
accomplish the task of transferring the n disks from tower 1 to tower 3 is as follows:
#include <stdio.h>
#include <conio.h>
int cnt=0;
Lecture Notes 17
Lecture Notes: Golam Moktader Daiyan, Assistant Prof., East Delta University
RUN 1:
RUN 2:
A Fibonacci sequence starts with the integers 0 and 1. Successive elements in this
sequence are obtained by summing the preceding two elements in the sequence. For
example, third number in the sequence is 0 + 1 = 1, fourth number is 1 + 1= 2, fifth
number is 1 + 2 = 3 and so on. The sequence of Fibonacci integers is given below:
0 1 1 2 3 5 8 13 21 . . . . . . . . .
Lecture Notes 18
Lecture Notes: Golam Moktader Daiyan, Assistant Prof., East Delta University
A recursive definition for the Fibonacci sequence of integers may be defined as follows:
Fib (n) = n if n = 0 or n = 1
Fib (n) = fib (n-1) + fib (n-2) for n >=2
1 + 0 + 1 + 1 + 0 + fib(2) + fib(1)
1+0+1+1+0+1+0+1=5
We see that fib(2) is computed 3 times, and fib(3), 2 times in the above calculations.
We save the values of fib(2) or fib(3) and reuse them whenever needed.
A recursive function to compute the Fibonacci number in the nth position is given below:
main()
{
clrscr ();
printf (“=nfib(5) is %d”, fib(5));
}
fib(n)
int n;
{
int x;
if (n==0 | | n==1)
return n;
x=fib(n-1) + fib(n-2);
return (x);
}
Output:
fib(5) is 5
Lecture Notes 19
Lecture Notes: Golam Moktader Daiyan, Assistant Prof., East Delta University
#include<stdio.h>
float ncr (int n, int r);
void main()
{
int n, r, result;
printf(“Enter the value of N and R :”);
scanf(“%d %d”, &n, &r);
result = ncr(n, r);
printf(“The NCR value is %.3f”, result);
}
Output:
#include<stdio.h>
void main()
{
int a[20], status, i, n, prime;
printf (“Enter the limit: “);
scanf(“%d”, &n);
printf (“Enter the numbers : “);
for (i = 0; i < n; i++)
scanf(“%d”, &a[i]);
printf (“The least common multiple is %ld”, lcm(a, n, 2));
}
Lecture Notes 20
Lecture Notes: Golam Moktader Daiyan, Assistant Prof., East Delta University
Output:
#include<stdio.h>
void main()
{
int a[20], stat, i, n, prime;
printf (“Enter the limit: “);
scanf (“%d”, &n);
printf (“Enter the numbers: “);
for (i = 0; i < n; i ++)
scanf (“%d”, &a[i]);
printf (“The greatest common divisor is %ld”, gcd (a, n, 2));
}
Lecture Notes 21
Lecture Notes: Golam Moktader Daiyan, Assistant Prof., East Delta University
Output: