0% found this document useful (0 votes)
1 views

Recursion

Uploaded by

suritdey2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Recursion

Uploaded by

suritdey2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Programming for Problem Solving (PPS)

BCAC 102
USING

{C}
Recursion Programming

Sudip Barik
Department of Computer Application
Techno International New Town
What is Recursion?
 Any function which calls itself is called recursive function and such function calls
are called recursive calls.
 Recursion cannot be applied to all problems, but it is more useful for the tasks that
can be defined in terms of a similar subtask.
 It is idea of representing problem a with smaller problems.
 Any problem that can be solved recursively can be solved iteratively.
 When recursive function call itself, the memory for called function allocated and
different copy of the local variable is created for each function call.
 Some of the problem best suitable for recursion are
 Factorial
 Fibonacci
 Tower of Hanoi

Sudip Barik BCAC 102 (PPS) – Recursion 2


Recursion : chaining
 When a called function in turn calls another function a process of ‘chaining’ occurs.
Recursion is a special case of this process, where a function calls itself.
 A very simple example of function chaining is presented below:
Program Output
1 #include <stdio.h> This is main function
2 void main()
This is function: fun1
3 {
4 printf("This is main function\n");
This is function: fun2
5 fun1();
6 }
main( ) fun1( ) fun2( )
7 void fun1()
8 {
9
... ... ...
printf("This is function: fun1\n");
... 1 ... 2 ...
10 fun2();
11 } fun1( ); fun2( ); ...
12 void fun2() ... ... ...
13 { ... 4 ... 3 ...
14 printf("This is function: fun2\n");
15 }
Sudip Barik BCAC 102 (PPS) – Recursion 3
How recursion works?
Program
 In C programming, every function call causes C 1 #include <stdio.h>
runtime to load function local variables and return 2 void main()
address to caller function on stack (memory). Each 3 {
recursive call will load a fresh copy of local variables 4
5
printf(“Test...\n");
main();
and return address to stack. 6 }

 In any recursive function call, the return address to


caller function is loaded to stack for each function call. Return address of main( )
 Since memory is a limited resource, loading of return Return address of main( )
addresses indefinitely will result in memory shortage.
Return address of main( )
In this situation, Operating System will either allocate
more memory for our program or will terminate the Return address of main( )
program abnormally. Which is what happened in the Return address of main( )
given recursive program.
Return address of main( )

STACK
Sudip Barik BCAC 102 (PPS) – Recursion 4
Working of Recursive function
Working
void func1();

void main()
{
....
func1(); Return address of func1( )
.... Function
} call Return address of func1( )

void func1() Return address of func1( )


{ Recursive
Return address of func1( )
.... function call
func1(); Return address of func1( )
....
} Return address of main( )

STACK
Sudip Barik BCAC 102 (PPS) – Recursion 5
Recursion : infinite call
 When a recursive function directly calls itself (or indirectly by another function)
without any base condition(or terminating condition) then infinite recursion occurs.
 A very simple example of infinite recursion call is presented below:

Program
1 #include <stdio.h>
2 void main()
3 {
4 printf("This is an example of recursion\n");
5 main();
6 }

Output
This is an example of recursion
This is an example of recursion Execution must be terminated abruptly; otherwise
This is an example of recursion the execution will continue indefinitely.
. . . . .

Sudip Barik BCAC 102 (PPS) – Recursion 6


Recursion : Characteristics
 Recursive functions can be effectively used to solve problems where solution is
expressed in terms of successively applying the same solution to subsets of the
problem.
 When we write recursive functions, we must have an if statement somewhere to
force the function to return without the recursive call being executed. Otherwise,
the function will never return.
 Using recursive algorithm, certain problems can be solved quite easily.
 In any recursive program, the solution to the base case is provided and the
solution of the bigger problem is expressed in terms of smaller problems.
 A Data Structure called Stack is used for calling recursive functions.
 Recursion is a great tool in the hand of the programmers to code some problems
in a lot easier and efficient way.

Sudip Barik BCAC 102 (PPS) – Recursion 7


Properties of Recursion
 A recursive function can go infinite like a loop. To avoid infinite running of recursive
function, there are two properties that a recursive function must have.
 Base Case or Base criteria
 It allows the recursion algorithm to stop.
 A base case is typically a problem that is small enough to solve directly.
 Progressive approach
 A recursive algorithm must change its state in such a way that it moves forward to the base
case.

Sudip Barik BCAC 102 (PPS) – Recursion 8


Direct Recursion and Indirect Recursion
 Direct recursion occurs when a Direct Recursion
function calls itself. This results in a 1 int num()
one-step recursive call: the function 2 {
3 . . .
makes a recursive call inside its own 4 . . .
function body. 5 num();
6 }

 Indirect Recursion occurs when the Indirect Recursion


function invokes other function which 1 int num()

again causes the original function to be


2 {
3 . . .
called again. 4 sum();
5 }
6 int sum()
7 {
8 . . .
9 num();
10 }

Sudip Barik BCAC 102 (PPS) – Recursion 9


Difference : Direct & Indirect Recursion
Direct Recursion Indirect Recursion
In the direct recursion, only one function is called by In indirect recursion more than one function are called
itself. by the other function and number of times.

The direct recursion called by the same function. The indirect function called by the other function.

In direct function, when function called next time, value In indirect recursion, value of the local variable will
of local variable will stored. automatically lost when any other function is called.

Direct function engaged memory location. The local variable of indirect function not engaged it.

Sudip Barik BCAC 102 (PPS) – Recursion 10


Difference : Recursion & Iteration
Property Recursion Iteration

Definition Function calls itself. A set of instructions repeatedly executed.

Application For functions. For loops.

Through base case, where there will be no When the termination condition for the
Termination
function call. iterator ceases to be satisfied.

Used when code size needs to be small, and Used when time complexity needs to be
Usage
time complexity is not an issue. balanced against an expanded code size.

Code Size Smaller code size Larger Code Size.

Very high(generally exponential) time Relatively lower time complexity(generally


Time Complexity
complexity. polynomial-logarithmic).

Sudip Barik BCAC 102 (PPS) – Recursion 11


Recursion - factorial example
 The factorial of a integer n, is Recursive trace
product of
 n * (n-1) * (n-2) * …. * 1 Final Ans 5 *24 = 120

 Recursive definition of factorial Fact(5)


 n! = n * (n-1)! call
return 4 * 6 = 24
 Example
 3! = 3 * 2 * 1 Fact(4)
return 3 * 2 = 6
 3! = 3 * (2 * 1) call
 3! = 3 * (2!)
Fact(3)
return 2 * 1 = 2
call
Fact(2)
return 1
call
Fact(1)

Sudip Barik BCAC 102 (PPS) – Recursion 12


WAP to find factorial of given number using Recursion
Program Output
1 #include <stdio.h> Enter the number? 5
2 int fact(int); factorial = 120
3 void main()
4 {
5 int n, f;
6 printf("Enter the number?\n");
7 scanf("%d", &n);
8 f = fact(n);
9 printf("factorial = %d", f);
10 }
11 int fact(int n)
12 {
13 if (n == 0)
14 return 1;
15 else if (n == 1)
16 return 1;
17 else
18 return n * fact(n - 1);
19 }

Sudip Barik BCAC 102 (PPS) – Recursion 13


Recursion - Fibonacci example
 A series of numbers , where next Recursive trace
number is found by adding the two
number before it. Fib(4) Final Ans. 3

 Recursive definition of Fibonacci return 2 return 1


 Fib(0) = 0
 Fib(1) = 1 Fib(3) Fib(2)
 Fib(n) = Fib(n-1) + Fib(n-2)
return 1 return 1 return 0
 Example return 1
Fib(2) Fib(1) Fib(1) Fib(0)
 Fib(4) = Fib(3) + Fib(2)
 Fib(4) = 3
return 1 return 0
Fib(1) Fib(0)

Sudip Barik BCAC 102 (PPS) – Recursion 14


WAP to Display Fibonacci Sequence
Program Program contd.
1 #include <stdio.h> 15 int fibonacci(int n)
2 int fibonacci(int); 16 {
3 void main() 17 if (n == 0 || n == 1)
4 { 18 return n;
5 int n, m = 0, i; 19 else
6 printf("Enter Total terms\n"); 20 return (fibonacci(n - 1) +
7 scanf("%d", &n); fibonacci(n - 2));
8 printf("Fibonacci series\n"); 21 }
9 for (i = 1; i <= n; i++)
10 { Output
11 printf("%d ", fibonacci(m)); Enter Total terms
12 m++; 5
13 } Fibonacci series
14 } 0 1 1 2 3

Sudip Barik BCAC 102 (PPS) – Recursion 15


Recursion - Decimal to Binary example
 To convert decimal to binary, divide Recursive trace
decimal number by 2 till dividend
will be less then 2 Final Ans 13%2 + 10*110 = 1101
 To convert decimal 13 to binary decToBin(13)
 13/2 = 6 reminder 1 return 6%2 + 10*11 = 110
call
 6/2 = 3 reminder 0
 3/2 = 1 reminder 1 decToBin(6)
 1/2 = 1 reminder 1 call
return 3%2 + 10*1 = 11

 Recursive definition of Decimal to decToBin(3)


Binary return 1%2 + 10*0 = 1
call
 decToBin(0) = 0
 decToBin(n) = n%2 + 10* decToBin(n/2) decToBin(1)

 Example call
return 0

 decToBin(13) = 13%2 + 10 decToBin(6) decToBin(0)


 decToBin(13) = 1101
Sudip Barik BCAC 102 (PPS) – Recursion 16
WAP to Convert Decimal to Binary
Program Output
1 #include <stdio.h> Enter a decimal number: 12
2 int convertDecimalToBinary(int); The binary equivalent = 1100
3 void main()
4 {
5 int dec, bin;
6 printf("Enter a decimal number: ");
7 scanf("%d", &dec);
8 bin = convertDecimalToBinary(dec);
9 printf("The binary equivalent = %d \n",bin);
10 }
11 int convertDecimalToBinary(int dec)
12 {
13 if (dec == 0)
14 return 0;
15 else
16 return (dec % 2 + 10 *
convertDecimalToBinary(dec / 2));
17 }

Sudip Barik BCAC 102 (PPS) – Recursion 17


WAP to Convert Binary to Decimal
Program Output
1 #include <stdio.h> Enter a binary number: 101
2 int convertBinaryToDecimal(int b, int c, int t); Decimal value of 101 is 5
3 void main()
4 {
5 unsigned int binary, decimal;
6 printf("Enter a binary number: ");
7 scanf("%d", &binary);
8 decimal = convertBinaryToDecimal(binary, 1, 0);
9 printf("Decimal value of %d is %d", binary, decimal);
10 }
11 int convertBinaryToDecimal(int b, int c, int t)
12 {
13 if (b > 0)
14 {
15 t += (b % 10) * c;
16 convertBinaryToDecimal(b / 10, c * 2, t);
17 }
18 else
19 return t;
20 }

Sudip Barik BCAC 102 (PPS) – Recursion 18


Ackermann Function
 The Ackermann function, named after Wilhelm Ackermann, is one of the
simplest and earliest-discovered examples of a recursive function.
 It’s a function with two arguments each of which can be assigned any non-
negative integer.
 Ackermann function is defined as:

Sudip Barik BCAC 102 (PPS) – Recursion 19


Ackermann Function : C Program
Program
1 #include <stdio.h> Output
2 int ack(int m, int n)
3 { 4
4 if (m == 0){
5 return n+1;
6 }
7 else if((m > 0) && (n == 0)){
8 return ack(m-1, 1);
9 }
10 else if((m > 0) && (n > 0)){
11 return ack(m-1, ack(m, n-1));
12 }
13 }
14 int main(){
15 int A;
16 A = ack(1, 2);
17 printf("%d", A);
18 return 0;
19 }

Sudip Barik BCAC 102 (PPS) – Recursion 20


Ackermann Function : Step by Step solution
 Solve A(1, 2)?  Now put this value in equation 3
Hence A(1, 0) = 2
 Answer:
Now put this value in equation 2
 Given problem is A(1, 2) A(1, 1) = A(0, 2) ———- (4)
Here m = 1, n = 2 e.g m > 0 and n > 0 Now, Let’s find A(0, 2) by applying first
Hence applying third condition of Ackermann condition of Ackermann function
function A(0, 2) = 2 + 1 = 3
A(1, 2) = A(0, A(1, 1)) ———- (1) Now put this value in equation 4
Now, Let’s find A(1, 1) by applying third Hence A(1, 1) = 3
condition of Ackermann function Now put this value in equation 1
A(1, 1) = A(0, A(1, 0)) ———- (2) A(1, 2) = A(0, 3) ———- (5)
Now, Let’s find A(1, 0) by applying second Now, Let’s find A(0, 3) by applying first
condition of Ackermann function condition of Ackermann function
A(1, 0) = A(0, 1) ———- (3) A(0, 3) = 3 + 1 = 4
Now, Let’s find A(0, 1) by applying first Now put this value in equation 5
condition of Ackermann function Hence A(1, 2) = 4
A(0, 1) = 1 + 1 = 2
 So, A (1, 2) = 4

Sudip Barik BCAC 102 (PPS) – Recursion 21


Disadvantages of Recursion
 A recursive program has greater space requirements than an iterative program as each function call
will remain in the stack until the base case is reached.
 It also has greater time requirements because each time the function is called, the stack grows and
the final answer is returned when the stack is popped completely.
 Recursive functions are complex to read, write and understand.
 Bugs in a recursive function are difficult to trace and remove.
 If the system Stack size is small then there is a chance of Stack Overflow.
Program
function( ) will be pushed into stack for
1 #include <stdio.h> infinite time as there is no termination
2 void main() condition
3 {
4 printf(“Stack Overflow by infinite recursion”); function()
5 function(); function()
6 }
7 void function() function()
8 { function()
9 function();
10 } main()
Sudip Barik BCAC 102 (PPS) – Recursion 22
Advantages of Recursion
 For a recursive function, you only need to define the base case and recursive case,
so the code is simpler and shorter than an iterative code.
 Some problems are inherently recursive, such as Graph and Tree Traversal.
 Using recursion many complex mathematical problems can be solved easily.
 Using recursion, a problem can be solved in less number of programming
construct, compared to its iterative counterpart.

Recursion makes code smaller Some data structure problems can


only be solved through recursion!

Sudip Barik BCAC 102 (PPS) – Recursion 23


When not to use recursion?
 Essentially, any problem that can be solved by recursion can be also solved by
iteration. Although for certain applications like Tower of Hanoi, certain artificial
intelligence problems etc recursion is used since it defines the problem naturally,
still there are certain times when recursion should not be used.
 Iterations are faster than their recursive counterparts. So, for speed we would
normally use iteration.
 If the stack size limit is constraining then we will prefer iteration over recursion.
 Some problems are naturally programmed recursively, here recursion would suit
better.
 The overhead involved in recursion in terms of time and space consumed both
discourages to use recursion often.

Sudip Barik BCAC 102 (PPS) – Recursion 24


Recursion : unreachable code ?
 Unreachable code, a part of the source code that will never be executed due to
inappropriate exit points or control flow in the program.
Program
1 void recursive_function() In this example, main() function is executed
2 {
3 // Some codes first, it calls recursive_function().
4
5 recursive_function(); The recursive_function() executes some
6
7 // Unreachable code code and call itself. The process continues i.e.
8 } calling of recursive_function() function from
9 int main() recursive_function() itself and behaves as an
10 {
11 recursive_function(); infinite loop. Finally, execution of above
12 } program terminates in a crash.

Sudip Barik BCAC 102 (PPS) – Recursion 25


Dead Code
 Dead code is a kind of unreachable code, although dead code might get executed
but has no effect on the functionality of the system.
 Below example clearly shows unreachable code and dead code differences:

Dead Code Example Unreachable Code Example


1 int add(int x, int y) 1 int add(int x, int y)
2 { 2 {
3 int z = x * y; 3 return (x + y);
4 return (x + y); 4 int z = x * y;
5 } 5 }
Sudip Barik BCAC 102 (PPS) – Recursion 26
Unreachable Code & Dead Code : Side Effects
 Unnecessary memory overheads.
 Unnecessary caching cycles which leads to performance bottlenecks.
 Documenting and Maintaining overheads.
 Difficult to debug code.

Unreachable Code & Dead Code : Causes


 Programming errors while developing complex conditional branches.
 Incomplete unit testing because of which unreachable code was undetected.
 Redundant code that developer forgot to delete.
 The code that might be programmatically correct but won't be executed at any
point of time due to the input data that is passed to the function.

Sudip Barik BCAC 102 (PPS) – Recursion 27


Tail Recursion
 A recursive function is tail recursive when recursive call is the last thing executed by
the function.
 For example the following C function print( ) is tail recursive.

Program
1 // An example of tail recursive function
2 void print(int n)
3 {
4 if (n < 0) return;
5 printf(“ %d”, n);
6
7 // The last executed statement is recursive call
8 print(n-1);
9 }

Sudip Barik BCAC 102 (PPS) – Recursion 28


Tail Recursion : why better ?
 The tail recursive functions considered better than non tail recursive functions as
tail-recursion can be optimized by compiler.
 The idea used by compilers to optimize tail-recursive functions is simple, since the
recursive call is the last statement, there is nothing left to do in the current
function, so saving the current function’s stack frame is of no use.

Sudip Barik BCAC 102 (PPS) – Recursion 29


Practice Programs
1) Write a program to find factorial of a given number using recursion.
2) WAP to convert decimal number into binary using recursion.
3) WAP to use recursive calls to evaluate F(x) = x – x3/3! + x5/5! – x7/7! + … + xn/n!

Sudip Barik BCAC 102 (PPS) – Recursion 30


Thank you

You might also like