Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion When performing a repetitive task either: a loop recursion

Similar presentations


Presentation on theme: "Recursion When performing a repetitive task either: a loop recursion"— Presentation transcript:

1 Recursion When performing a repetitive task either: a loop recursion
n! = n*(n-1)*...*1 with a loop int fact(int n) { int result = 1; int i; /* n! = 1*n*(n-1)*...*2 */ for(i=n; i>1; i--) result = result*i; return result; } 142 P -1

2 n! with a recursive function
int fact(int n) { int result = 1; /* n = n * (n-1)! for n>1*/ if (n>1) result = n*fact(n-1); return result; } What is going on? Recall that when calling a function, arguments are passed BY VALUE 142 P -2

3 An Example: Fact(4) fact(4) 24 (=4!) 4 n 4 * fact(3) result 6 3
n (different memory location) result 6 3 3 * fact(2) n result 2 2 2 * fact(1) 1 n result 1 1 142 P -3

4 Loop vs Recursion Any iterative algorithm (=Loop) can be
reworked to use recursion instead Some algorithms are more naturally written in terms of recursion However, recursion is generally more time consuming (overhead time) The computer needs to store the location in the program where the function is called { ... } int fact(int n) x = fact(n); Store the address of this statement to be able to come back here (store on the stack). 142 P -4

5 The Towers of Hanoi Move the tower of disks from the left to
the right peg You can't place a larger disk on top of a smaller one Very well suited to a recursion algorithm We know how to move 1 disk To move n disks, move n-1 and then 1 To move n-1 disks, move n-2 and then 1 ... 142 P -5

6 void move(int ndisks,int peginit, int pegfinal, int pegtemp) {
Write a function: move void move(int ndisks,int peginit, int pegfinal, int pegtemp) { /* move ndisks from peginit to pegfinal, using pegtemp as a temporary holding area */ if (ndisks ==1) {/* easy! */} else /*move ndisks -1 to pegtemp*/ move(ndisks-1,peginit,pegtemp,pegfinal); /*move the remaining disk to pegfinal*/ move(1,peginit,pegfinal,pegtemp); /*move ndisks -1 to pegfinal*/ move(ndisks-1,pegtemp,pegfinal,peginit); } 142 P -6

7 Another example Getting 'y' or 'n' from the user: char yes_or_no(void)
{ char answer; printf("Enter 'y' or 'n': "); scanf("%c",&answer); if (answer!='y' && answer!='n') /* flush the buffer */ fflush(stdin); /* ask again */ answer = yes_or_no(); } return answer; 142 P - 7


Download ppt "Recursion When performing a repetitive task either: a loop recursion"

Similar presentations


Ads by Google