Download presentation
Presentation is loading. Please wait.
1
CS 202 Computer Science II Lab Fall 2009 October 29
2
Today Topics Makefile Recursion
3
Makefile main.out: main.o stack$(VAL).o g++ -o main.out main.o stack$(VAL).o main.o: main.cpp stack$(VAL).h g++ -c main.cpp Stack$(VAL).o: stack$(VAL).cpp stack$(VAL).h g++ -c stack$(VAL).cpp $ make VAL=1 $ make VAL=2
4
Recursion –A method of specifying a process by means of itself. Recursive Function –A way of defining a function using recursion. Example F(x) = 30x + 7 Direct Implementation F(x) = F(x-1) - 30 Recursion Implementation
5
Recursion Base Case of a Recursively Defined Function – A value or values for which the recursive function is concretely defined. xF(x) 07 137 267 397 F(x) = 30x + 7 Base case: F(0) = 7
6
Recursion Recursive Algorithm: – An algorithm that calls itself with smaller and smaller subsets of the original input, doing a little bit or work each time, until it reaches the base case. int F(int x) { if (x=0) return 7; else return F(x-1) + 30; } int F(int x) { return (x= =0) ? 7 : F(x-1)+30; }
7
Recursion Example factorial(n) n! = nx(n-1)x(n-2)x…x2x1 Direct Imp. n! = nx(n-1)! Recursive Imp. Base case: If n = 0 then factorial(n) = 1 int factorial(int n) { if (n>0) return n*factorial(n-1); else return 1; } int factorial(int n) { return (n) ? n*factorial(n-1) : 1; }
8
Recursion Example Fibonacci numbers A sequence of numbers named after Leonardo of Pisa, known as Fibonacci. 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 … If n = 0 thenfib(n) = 1 If n = 1 thenfib(n) = 1 If n > 1 thenfib(n) = fib(n - 1) + fib(n - 2)
9
Recursion Example Fibonacci numbers int fib(int n) { if (n==0 or n==1) { return 1; } else { return fib(n-1)+fib(n-2); } }
10
Recursion Example The greatest common divisor (GCD) of two integers m and n int tryDivisor(int m, int n, int g){ if ( ( (m % g) == 0 ) && ( (n % g) == 0 ) ) return g; else return tryDivisor(m, n, g - 1); } int gcd(int m, int n) { return tryDivisor(m, n, n); //use n as our first guess } gcd(6, 4) tryDivisor(6, 4, 4) tryDivisor(6, 4, 3) tryDivisor(6, 4, 2) => 2
11
GCD int gcd(int m, int n) { if(m == n) return m; elseif (m > n) return gcd(m-n, n); else return gcd(m, n-m); } gcd(468, 24) gcd(444, 24) gcd(420, 24)... gcd(36, 24) gcd(12, 24) (Now n is bigger) gcd(12, 12) (Same) => 12
12
Extremely Smart way to compute GCD int gcd(int m, int n) { if ( (m % n) == 0 ) return n; else return gcd(n, m % n); } gcd(468, 24) gcd(24, 12) => 12 gcd(135, 19) gcd(19, 2) gcd(2, 1) => 1
13
Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.