5 views

Uploaded by Virendra Singh

computrt

save

- Amazon Hiring Process Tips
- TBB1073_-_SPDB05
- AppliedBinaryCodeObfuscation
- embedded 3
- x86_newnew
- UNIT-4.pdf
- microprocess
- Introduction to Porgramming Using Fortran-Ed Jorgensen
- Interrupts
- Computer Science 37 Lecture 13
- Introduction to Programming Using Fortran 95-2003-2008
- 05 Simple Recursion
- C New Sylbus
- Professional Posters
- bc: an arbitrary precision calculator language
- x64-intro
- 0672325314
- Script document
- Assembler p7
- 10 a Modified Extended Recursive Least-Squares Method for Identification of FIR Type Models From Closed-Loop Data
- Macro Processors
- Untitled
- About Kakuro
- HDUG 4 Recursive SQL
- At Mega 1281 Unlocked
- 7
- idx_f.pdf
- c++ programs for chemical engineering
- Tally ERP 9 to SQL Server
- 1756-pm014_-en-p
- Chem Quest
- BMGG
- Least Squares Fitting Method
- BMGG2
- BMGG1
- Fee Receipt View
- Geo Dynamo
- Lesson 3 Random Notes
- Hdr 2013 en Technotes
- Ebay
- Asia Regional Report 2012
- battlecase1(1)
- basic EC

You are on page 1of 49

**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

return address

factorial(4) 4

return address

factorial(4) 4 factorial(3) 3

n

return address

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

return address

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

return addr

return addressfactorial(4) return addressfactorial(3) return addressfactorial(2) return addressfactorial(1)

n n n

return address return address return address

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

return address

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

return addr

return addressfactorial(4) return addressfactorial(3) return addressfactorial(2)

n n

return address return address

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 addr

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

- Amazon Hiring Process TipsUploaded byAditya Ranjan
- TBB1073_-_SPDB05Uploaded byCyrus Hong
- AppliedBinaryCodeObfuscationUploaded byHarley Schenck
- embedded 3Uploaded byAtit Patel
- x86_newnewUploaded by曾于任
- UNIT-4.pdfUploaded byVenkatesan Swamy
- microprocessUploaded bychadobrien
- Introduction to Porgramming Using Fortran-Ed JorgensenUploaded byricardo
- InterruptsUploaded bymayuriprajapati
- Computer Science 37 Lecture 13Uploaded byAlexander Taylor
- Introduction to Programming Using Fortran 95-2003-2008Uploaded byPedro Aires
- 05 Simple RecursionUploaded bySudarshan Muralidhar
- C New SylbusUploaded byadddata
- Professional PostersUploaded bymr_mathyou_83
- bc: an arbitrary precision calculator languageUploaded byJeff Pratt
- x64-introUploaded bypitmikpado
- 0672325314Uploaded byx1y2z3q
- Script documentUploaded bysuryaredi123
- Assembler p7Uploaded byAyad M Al-Awsi
- 10 a Modified Extended Recursive Least-Squares Method for Identification of FIR Type Models From Closed-Loop DataUploaded byxinghust
- Macro ProcessorsUploaded byAjay Sohal
- UntitledUploaded byapi-126697740
- About KakuroUploaded byPericoSugar
- HDUG 4 Recursive SQLUploaded bysp40694
- At Mega 1281 UnlockedUploaded byHector Ledesma III
- 7Uploaded bySohaib Khalid
- idx_f.pdfUploaded byAnonymous ElCqwCGC
- c++ programs for chemical engineeringUploaded byGokul Kadam
- Tally ERP 9 to SQL ServerUploaded byKumar Pandurangan
- 1756-pm014_-en-pUploaded bypjl112008

- Chem QuestUploaded byVirendra Singh
- BMGGUploaded byVirendra Singh
- Least Squares Fitting MethodUploaded byVirendra Singh
- BMGG2Uploaded byVirendra Singh
- BMGG1Uploaded byVirendra Singh
- Fee Receipt ViewUploaded byVirendra Singh
- Geo DynamoUploaded byVirendra Singh
- Lesson 3 Random NotesUploaded byVirendra Singh
- Hdr 2013 en TechnotesUploaded byVirendra Singh
- EbayUploaded byVirendra Singh
- Asia Regional Report 2012Uploaded byVirendra Singh
- battlecase1(1)Uploaded byVirendra Singh
- basic ECUploaded byVirendra Singh