Recursion: Source: Pearson Addison-Wesley.
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
"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.,)
(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
)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