Lecture 12 Recursion

  • Upload
    nida

  • View
    235

  • Download
    0

Embed Size (px)

Citation preview

  • 8/9/2019 Lecture 12 Recursion

    1/21

    Data structures

    Lecture No. 12

    Dr. SeemabLatif 

    Recursion

  • 8/9/2019 Lecture 12 Recursion

    2/21

     Today’s Lecture

    In this lecture we will:

    study recursion. Recursion is aro!rammin! techni"ue in whichrocedures and functions callthemsel#es.

    loo$ at the stac$ % a structuremaintained by each ro!ram at runtime.

    2

  • 8/9/2019 Lecture 12 Recursion

    3/21

  • 8/9/2019 Lecture 12 Recursion

    4/21

    Introduction

    In //) any function can call another function.

    + function can e#en call itself.

    &hen a function call itself) it is ma$in! a recursi#ecall.

    Recursive Call  A function call in which the function being called is the

    same as the one making the call.

    Recursion is a owerful techni"ue that can be used in

    the lace of iteration0looin!. Recursion  Recursion is a programming technique in which

    procedures and functions call themselves.

  • 8/9/2019 Lecture 12 Recursion

    5/21

  • 8/9/2019 Lecture 12 Recursion

    6/21

    ,3amle 1

    &e can write a function called power that calculates theresult of raisin! an inte!er to a ositi#e ower. If 5 is aninte!er and N is a ositi#e inte!er) the formula for is

    &e can also write this formula as

    +lso as

    In fact we can write this formula as

    6

    times N 

     N  X   X   X   X   X   X   X  

    =   *....*****

    times N  

     N   X   X   X   X   X   X   X  

     _ )1(

    *....*****−

    =

    times N  

     N   X   X   X   X   X   X   X  

     _ )2(

    *.....*****−

    =

    1

    *  −

    =

     N   N  

     X   X   X  

  • 8/9/2019 Lecture 12 Recursion

    7/21

    ,3amle 10Recursi#e 7ower 8unction

    Now lets suose that 59-and N9

    Now we can simlify the

    abo#e e"uation as

    So the base case in thise"uation is

    int ower ! int " # int

    n $%

    if ! n && ' $

      return "( ))Basecase

    else

      return " * ower !"#n+'$(

      )) recursive call

    ,

    43= N   X  

    34 3*33   =

    23 3*33   =12 3*33   =

    331=

  • 8/9/2019 Lecture 12 Recursion

    8/21

    8actorial** + ase Study 8actorial 8unction: ;i#en a ositi#e inte!er n) n

    factorial is de(ned as the roduct of all inte!ersbetween 1 and n) includin! n.

    De(nition: n< 9 n= 0n*1= 0n*2 = >>..=1

    ?athematical De(nition:

    Imlementation usin! loo

    @

  • 8/9/2019 Lecture 12 Recursion

    9/21

    8actorial ase Study

    8actorial de(nition

    n< 9 n A n*1 A n*2 A n*- A > A - A 2 A 1

    B< 9 1

     To calculate factorial of n◦ Case case

    If n 9 B) return 1

    ◦ Recursi#e ste

    alculate the factorial of n*1

    Return n A 0the factorial of n*1

  • 8/9/2019 Lecture 12 Recursion

    10/21

    8actorial ase Study

    int factorial0n

    Eif0n F9 1 GGCase ase

      return 1H

    else

      return n = factorial0n*1H GGRecursion 1B

    Jere’s a function that comutes the factorial of a

    number N without usin! a loo.

     It chec$s whether N is smaller than 1. If so) the

    function Kust returns 1.

     therwise) it comutes the factorial of N M 1 and

    multilies it by N.

  • 8/9/2019 Lecture 12 Recursion

    11/21

    ,#aluation of 8actorial ,3amle

     To e#aluate 8actorial0-e#aluate - = 8actorial02

     To e#aluate 8actorial02

    e#aluate 2 = 8actorial01

     To e#aluate 8actorial01e#aluate 1 = 8actorial0B

    8actorial0B is 1

    Return 1

    ,#aluate 1 = 1

    Return 1

    ,#aluate 2 = 1

    Return 2

    ,#aluate - = 2

    Return 611

  • 8/9/2019 Lecture 12 Recursion

    12/2112

    Recursi#e 7ro!rammin!

    main

    factorial(3)

    factorial(2)

    factorial(1)

    factorial(3)

    2*factorial(1)

    3 * factorial(2)

    return 1

    return 6

    1*factorial(0)

    factorial(0)

    return 1

    return 2

  • 8/9/2019 Lecture 12 Recursion

    13/21

    +nother ,3amle**1

    Jere is a function torint all the elements ofa lin$ed list.

    !et8romList0e3tractsone item from the head

    of the list and thanreturn the its #alue. Inaddition) it also return anew ointer ointin! torest of the list NTinclude the returneditem.

    rint+ll0dislays on theconsole +LL the items

    stored in the entirelin$ed list. It terminates 1-

    int get-romist !/odeptr0hdist$%

    int number(number &

    hdist

    data(hdist & istne"t(return !number$

    ,1oid printAll !/odeptr

    hdist$%

    cout223ist ofnumbers are:4(

    while !hdist 5& /6$

    %

  • 8/9/2019 Lecture 12 Recursion

    14/21

    +nother ,3amle**2

     The function below rints out the numbers in alist of numbers. 'nli$e the #ersion of rint+ll inre#ious side) it doesn’t use a loo. This is how itwor$s.

    ◦ It rints out the (rst number in the list.

    ◦  Then it calls itself to rint out the rest of the list.

    ◦ ,ach time it calls itself) the list is a bit shorter.

    ◦ ,#entually we reach an emty list) and the whole

    rocess terminates.

    1

  • 8/9/2019 Lecture 12 Recursion

    15/21

    isualiOation

    14

  • 8/9/2019 Lecture 12 Recursion

    16/21

    Rules 8or Recursi#e 8unction

    1. In recursion) it is essential for a function to call itself)otherwise recursion will not ta$e lace.

    2. nly user de(ne function can be in#ol#ed in recursion.

    -.  To sto the recursi#e function it is necessary to base therecursion on test condition and roer terminatin!

    statement such as exit() or return must be written usin!if0 statement.

    . &hen a recursi#e function is e3ecuted) the recursi#ecalls are not imlemented instantly. +ll the recursi#ecalls are ushed onto the stac$ until the terminatin!condition is not detected) the recursi#e calls stored inthe stac$ are oed and e3ecuted.

    4. Durin! recursion) at each recursi#e call new memory isallocated to all the local #ariables of the recursi#e

    functions with the same name. 16

  • 8/9/2019 Lecture 12 Recursion

    17/21

     The Runtime Stac$ durin! Recursion

     To understand how recursion wor$s at run time)we need to understand what haens when afunction is called.

     &hene#er a function is called) a bloc$ of memoryis allocated to it in a run*time structure called thestack.

     This bloc$ of memory will contain

    ◦ the function’s local variables#

    ◦   local coies of the function’s call+b7+valueparameters#

    ◦ ointers to its call+b7+reference parameters) and

    ◦ a return address# in other words where in the1

  • 8/9/2019 Lecture 12 Recursion

    18/21

    Crain Stormin!

  • 8/9/2019 Lecture 12 Recursion

    19/21

    Recursion: 8inalRemar$s

     The tric$ with recursion is to ensure that eachrecursi#e call !ets closer to a base case. In most ofthe e3amles we’#e loo$ed at) the base case is theemty list) and the list !ets shorter with each

    successi#e call.Recursion can always be used instead of a loo. 0This

    is a mathematical fact. In declarati#e ro!rammin!lan!ua!es) li$e 7rolo!) there are no loos. There isonly recursion.

     Recursion is ele!ant and sometimes #ery handy) butit is mar!inally less eQcient than a loo) because ofthe o#erhead associated with maintainin! the stac$.

    1

  • 8/9/2019 Lecture 12 Recursion

    20/21

    ,3ercise

     The roblem of comutin! the sum of all thenumbers between 1 and any ositi#e inte!er Ncan be recursi#ely de(ned as:

    2B

    i = 1

     N

    i = 1

     N-1

    i = 1

     N-2

    = N + = N + (N-1) +

    = etc.

  • 8/9/2019 Lecture 12 Recursion

    21/21

    ,3ercise

    int sum0int n

    E

    if0n991

    return nH

    else

    return n / sum0n*1H

    21