You are on page 1of 49

# Functions

Programming & Data Structure
CS 11002 Partha Bhowmick http://cse.iitkgp.ac.in/˜pb
CSE Department IIT Kharagpur

Spring 2012-2013

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Callee : Caller

=

Bowler : Captain

Functions

Iter Rec Fibo

Functions
int f(){ ... } main(){ ... f(); ... } Here f is the callee function. main is the caller function, which calls f().
PB | CSE IITKGP | Spring 2012-2013 PDS

(1)

Functions

Iter Rec Fibo

Computation of sinx
x3 x5 x7 x9 + − + ··· sin x = x − 3! 5! 7! 9! 2i+1 x = (−1)i (2i + 1)! i 0 =
i 0

(1)

x2i+1 ti , where ti = (−1) (2i + 1)!
i

A ﬁnite number of terms of the above power series can be used to compute an approximate value of sin x, where x is in radian.
PB | CSE IITKGP | Spring 2012-2013 PDS

Functions

Iter Rec Fibo

Computation of sinx
Inductive Deﬁnitions x ti = Si = −ti−1
2

(2)

if i = 0, x if i > 0. 2i(2i + 1)

t0 if i = 0, Si−1 + ti if i > 0.

They are also called recurrence relations or recursive deﬁnitions.

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Computation of sinx
Inductive Deﬁnition ⇒ Iterative Process An iterative process of computation can be obtained from the inductive deﬁnition. Thus, an approximation of sin x is computed as Si , the sum from t0 to ti , as follows.
1 2

(3)

Start with initial values: t0 and S0 . Repeat the following two steps for i > 0:
1 2

Compute ti from ti−1 . Compute the next approximate value of sin x by computing Si from Si−1 and ti .

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Computation of sinx
Termination of Iteration The process is to be terminated after a ﬁnite number of iterations. The termination may be 1 after a ﬁxed number of iterations, or 2 after achieving a pre-speciﬁed accuracy.

(4)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Computation of sinx
#include <stdio.h> #include <math.h> int main() { float x, preErr, appErr, rad, term, sinx; int i = 1; printf("Enter the angle in degree: "); scanf("%f", &x); printf("Enter the Percentage Error: "); scanf("%f", &preErr); // Initialization rad = atan(1.0)*x/45.0; term = rad; sinx = term;

(5)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Computation of sinx
do { // Iteration float factor; factor = 2.0 * i++; factor *= (factor + 1.0); factor = - rad * rad / factor; sinx += (term = factor * term); appErr = 100.0*fabs(term/sinx); } while (appErr >= preErr); printf("\nsin(%f) = %55.50f\n#Iterations = %d\n", x, sinx, i - 1); return 0; } // sin.c

(6)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Computation of sinx

(7)

\$ cc -lm -Wall sin.c \$ ./a.out Enter the angle in degree: 90 Enter the Percentage Error: .1 sin(90.000000) = 1.00000345706939697265625000000000000000000000000000 #Iterations = 4 \$ ./a.out Enter the angle in degree: 90 Enter the Percentage Error: .01 sin(90.000000) = 0.99999988079071044921875000000000000000000000000000 #Iterations = 5
PB | CSE IITKGP | Spring 2012-2013 PDS

Functions

Iter Rec Fibo

Computation of sinx

(8)

\$ ./a.out Enter the angle in degree: 90 Enter the Percentage Error: .00001 sin(90.000000) = 0.99999994039535522460937500000000000000000000000000 #Iterations = 6 \$ ./a.out Enter the angle in degree: 90 Enter the Percentage Error: .000000000001 sin(90.000000) = 0.99999994039535522460937500000000000000000000000000 #Iterations = 10

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Computation of sinx
Caution! Notice the last two runs. The accuracy of the program decreases for large values of angle due to error propagation.

(9)

PB | CSE IITKGP | Spring 2012-2013

PDS

Recursion

To understand recursion, you must understand recursion.

Functions

Iter Rec Fibo

Recursion
Example: Factorial Function n! = or, f act(n) = 1 if n = 0, n × f act(n − 1) if n > 0. 1 if n = 0, n × (n − 1)! if n > 0.

(1)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Recursion
Example: Computation of 4! 4! = = = = = = = = 4 × 3! 4 × (3 × 2!) 4 × (3 × (2 × 1!)) 4 × (3 × (2 × (1 × 0!))) 4 × (3 × (2 × (1 × 1))) 4 × (3 × (2 × 1)) 4 × (3 × 2) 4 × 6 = 24
PDS

(2)

PB | CSE IITKGP | Spring 2012-2013

Functions

Iter Rec Fibo

Recursion
Features There is no value computation in the ﬁrst four steps, as the function is being unfolded. The value computation starts only after the basis of the deﬁnition is reached. Last four steps computes the values. Deﬁnition: Recursive Function A function that calls itself directly or indirectly is called a recursive function. Unfolding and delayed computation can be simulated by such a function.
PB | CSE IITKGP | Spring 2012-2013 PDS

(3)

Functions

Iter Rec Fibo

Recursion
Recursive Call A() call A call A call A → A() → A() → A() · · ·

(4)

As a recursive function calls itself, the obvious question is about its termination. The basis of the inductive (recursive) deﬁnition provides the condition for termination. The function calls itself to gradually reach the termination condition or the basis!

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Recursion
int fact(int n){ if (n == 0) return 1; else return n * fact(n-1);} fact(4) = 4 · fact(3) = 4 · (3 · fact(2)) = 4 · (3 · (2 · fact(1))) = 4 · (3 · (2 · (1 · fact(0)))) = 4 · (3 · (2 · (1 · 1))) = 4 · (3 · (2 · 1)) = · · · = 24.

(5)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Recursion
Functions during Recursive Calls For every call, there is new incarnation of all the formal parameters and the local variables (that are not static). The variable names get bound to diﬀerent memory locations. Variables of one invocation are not visible from another invocation. Once a return statement is executed, all the variables of the corresponding invocation die.

(6)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Recursion
The last incarnation of a variable name dies ﬁrst and the last call is returned ﬁrst—a principle called last in ﬁrst out (LIFO).

(7)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Stack Frame or Activation Record
main()
stack frame stack frame

(1)

x n

main()
stack frame

x n

factorial(4) 4

factorial(4) 4 factorial(3) 3

n

Stack Region
PB | CSE IITKGP | Spring 2012-2013 PDS

Stack Region

Functions

Iter Rec Fibo

Stack Frame or Activation Record
main()
stack frame

(2)

x n n n n n

main()
stack frame

x 4 3 2 1 n

factorial(4) 4 factorial(3) 3 factorial(2) 2 factorial(1) 1 factorial(0) 0

n n n

Return 1

Stack Region

Stack Region

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Stack Frame or Activation Record
main()
stack frame

(3)

x n n n n

main()
stack frame

x 4 3 2 n

factorial(4) 4 factorial(3) 3 factorial(2) 2 factorial(1) 1

n n

Return 1

Stack Region

Stack Region

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Stack Frame or Activation Record
main()
stack frame

(4)

x n

main()
stack frame

x

factorial(4) 4

Return 24

Stack Region

Stack Region

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Expensive side of recursive function
The recursive factorial function uses more memory than its non-recursive counterpart. The non-recursive function uses ﬁxed amount of memory for an int data, whereas the memory usage by the recursive function is proportional to the value of data. A function call and return takes some amount of extra time.

(1)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Recursive Function by Iteration!
Value computation in recursively deﬁned factorial function starts after unfolding the recursion. But we can redesign the function so that it can start the computation from the beginning. int factIter(int n) { int acc = 1, i; for(i = n; i > 0; --i) acc *= i; return acc;}

(1)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

gcd(m, n)
Inductive Deﬁnition & Recursive Function n if m = 0, gcd(n mod m, m) if m > 0.

(1)

gcd(m, n)|m

n

=

int gcd(int m, int n){ // m <= n if(m == 0) return n; return gcd(n%m, m);}

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

gcd(m, n)
Diﬀerent Calls to gcd() gcd(0, 0) ⇒ return 0 gcd(0, 5) ⇒ return 5 gcd(5, 0) ⇒ gcd(0, 5) ⇒ return 5 gcd(18, 12) ⇒ gcd(12, 18) ⇒ gcd(6, 12) ⇒ gcd(0, 6) ⇒ return 6
PB | CSE IITKGP | Spring 2012-2013 PDS

(2)

Functions

Iter Rec Fibo

Fibonacci Sequence
Fibonacci’s† question in the year 1202: How many pairs of rabbits will be there in a year from now? Conditions: Begin with 1 male and 1 female rabbit—just born—which reach sexual maturity after 1 month. The gestation period of a rabbit is 1 month. On reaching sexual maturity, a female rabbit gives birth to 1 male and 1 female rabbit in every month. Rabbits never die.

(1)

Leonardo Pisano Fibonacci (1170–1250, Pisa).
PB | CSE IITKGP | Spring 2012-2013 PDS

Functions

Iter Rec Fibo

Fibonacci Sequence

(2)

n 0 1 2 3 4 5 6 7 8 9 10 · · · ﬁb(n) 0 1 1 2 3 5 8 13 21 34 55 · · ·
PB | CSE IITKGP | Spring 2012-2013 PDS

Functions

Iter Rec Fibo

Fibonacci Sequence
0 1 1 2 3 5 8 13 21 34 ...

(3)

A tiling with squares whose side lengths are successive Fibonacci numbers.
PB | CSE IITKGP | Spring 2012-2013 PDS

Functions

Iter Rec Fibo

Fibonacci Sequence

(4)

Fibonacci spiral from golden rectangle of size 13 × 8.
(It starts at the left-bottom corner of the ﬁrst square (length 8) and passes through the farthest corners of succeeding squares.)
PB | CSE IITKGP | Spring 2012-2013 PDS

Functions

Iter Rec Fibo

Fibonacci Sequence

(5)

Romanesque brocolli (Roman cauliﬂower) is a striking example of the Fibonacci.
PB | CSE IITKGP | Spring 2012-2013 PDS

Functions

Iter Rec Fibo

Fibonacci Sequence

(6)

Spiral aloe. Numerous such cactus display the Fibonacci spiral.
PB | CSE IITKGP | Spring 2012-2013 PDS

Functions

Iter Rec Fibo

Fibonacci Sequence

(7)

Nautilus shell displays Fibonacci spiral.

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Fibonacci Sequence

(8)

Cancer cell division (mitosis) [Imaging by time-lapse microscopy.
The DNA is shown in red, and the cell membrane is shown in cyan.]
PB | CSE IITKGP | Spring 2012-2013 PDS

Functions

Iter Rec Fibo

Fibonacci Sequence
Inductive Deﬁnition ﬁbn = n if 0 ﬁbn−1 + ﬁbn−2 if n n<2 2.

(9)

And its direct coding results to: int fibr(int n){ // efficient? if(n < 2) return n; return fibr(n-1) + fibr(n-2); }

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Fibonacci Sequence
1 fibr(5) + 2 fibr(4) +

(10)

Recursion Tree (n = 5)

3 fibr(3) + 4 fibr(2) + 5 fibr(1) 1 1

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Fibonacci Sequence
1 fibr(5) + 2 fibr(4) + 3 fibr(3) + 4 fibr(2) + 5 fibr(1) 1 1 0 3 6 fibr(0) 2

(11)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Fibonacci Sequence
1 fibr(5) + 2 fibr(4) + 3 fibr(3) 7 + 4 fibr(2) 5 fibr(1) 1 + 3 6 fibr(0) 2 0 fibr(1) 4 1

(12)

1

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Fibonacci Sequence
1 fibr(5) + 2 fibr(4) + 8 3 fibr(3) 7 + 4 fibr(2) + 5 fibr(1) 1 1 0 fibr(2) 9

(13)

10 + fibr(1) fibr(1)fibr(0) 3 4 1 2 1 0

6 fibr(0)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Fibonacci Sequence
1 fibr(5) + 11 2 fibr(4) fibr(3) + 8 12 + 15 fibr(1) 3 fibr(3) fibr(2) fibr(2) + + 7 9 + 10 14 13 fibr(0) 1 4 fibr(2) fibr(1) fibr(1) fibr(0) fibr(1) + 6 1 0 5 1 0 1 fibr(1) fibr(0) 1 0

(14)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Fibonacci Sequence
Why bad? For n = 5, #calls = 15, #additions = 17. Better option Can be done by only n − 1 = 4 additions in an iterative program.

(15)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Fibonacci Sequence
Number of additions to compute ﬁbn by the previous recursive function: n 0 1 2 3 4 5 6 ··· ﬁbn 0 1 1 2 3 5 8 · · · addn 0 0 1 2 4 7 12 · · ·  if n = 0 or 1, 0 addn−1 + addn−2 + 1 addn =  = ﬁbn+1 − 1 if n > 1

(16)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Fibonacci Sequence
Why bad? When the recursive function is called with n as parameter, there will be n + 1 activation records (stack frames) present on the stack. On the contrary, for the iterative program, there is only a constant number of variables.

(17)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Fibonacci Sequence
Non-Recursive int fib(int n){ // non-recursive int i=1, f0=0, f1=1; if(n < 2) return n; for(i=2; i<=n; ++i) f1 += f0, f0 = f1 - f0; return f1;}
i 1 f1 1 f0 0 2 1 1 3 2 1 4 3 2 5 5 3 6 8 5 ... ... ...

(18)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

Fibonacci Sequence
An Eﬃcient Recursive Function We can write a recursive C function that will compute like the iterative program. This function has three parameters, and let it be called as fib(n,0,1), where 0 and 1 are base values corresponding to fib(0) and fib(1). int fib(int n, int f0, int f1) { if(n == 0) return f0; if(n == 1) return f1; return fib(n-1, f1, f1+f0);}
PB | CSE IITKGP | Spring 2012-2013 PDS

(19)

Functions

Iter Rec Fibo

Fibonacci Sequence
#include <stdio.h> int fib(int, int, int); int main() { int n; printf("Enter a non-ve integer: "); scanf("%d", &n); printf("fib(%d)=%d\n",n,fib(n,0,1)); return 0;}

(20)

PB | CSE IITKGP | Spring 2012-2013

PDS

Functions

Iter Rec Fibo

f0 1st call 5 n 0 1

f1 5

+
2nd call 3rd call 4th call 5th call 4 3 2 1 1 5 1 5 2 5 3 Return 3 5 2 1

PB | CSE IITKGP | Spring 2012-2013

PDS