Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Recursion

Source: Pearson Addison-Wesley..

Recursion
Recursion is the process of repeating items in a self-similar way. Computer programming languages support recursion by allowing a function to call itself within the program text

Stack for recursion


Since there is no a priori limit on the depth of nested recursive calls, we may need to save an arbitrary number of register values. These values must be restored in the reverse of the order in which they were saved, since in a nest of recursions the last subproblem to be entered is the first to be finished. This dictates the use of a stack, or structure, to save register values. last in, first out!! data

"e can extend the register-machine language to include a stack by adding two kinds of instructions# $alues are placed on the stack using a save instruction and restored from the stack using a restore instruction. %fter a se&uence of values has been saved on the stack, a se&uence of restores will retrieve these values in reverse order

Recursion - 'xample
#include<stdio.h> main() { int a, fact printf(!"n#nter any number$ !) scanf (!%d!, &a) fact'rec (a) printf(!"n(actorial )alue ' %d!, fact) getch() *

rec (int +) { int f if (+'',) { return (,) * else f'+-rec(+.,) return (f) *

'xecution (rocedure
rec(/.,) ' rec(,) return (,) return ',00 1o not return because more values are below f'/-rec(/.,) f'2-rec(2.,) f'3-rec(3.,) f'4-rec(4.,)

rec(2.,) rec(3.,) rec(4.,) rec(4)

(ibonacci se5uence
fib(n) int n { int +,y if(n <' ,) return (n) +'fib(n . ,) y'fib(n . /) return(+ 6 y) *

% Classical Case# Towers of )anoi The towers of Hanoi problem involves moving a
number of dis s !in different si"es# from one tower to another.

The constraint is that the larger dis can never be placed on top of a smaller dis . $nly one dis can be moved at each time Assume there are three towers available.

Source

Temp

*estination

% Classical Case# Towers of )anoi

)anoi towers
void solveTowers(int count, char source, char destination, char spare) { if (count == 1) { printf("Move top disk from pole %c to pole %c " ,source, ,destination); } else { solveTowers(count 1, source, spare, destination); !! " solveTowers(1, source, destination, spare); } } !! end if !! end solveTowers !! # solveTowers(count 1, spare, destination, source); !! $

Recursion tree# The order of recursive calls that results from solveTowers(3,A,B,C)

Thank +ou

You might also like