SlideShare a Scribd company logo
1 of 21
© 2012 Pearson Education, Inc. All rights reserved.

                                                  Chapter 15:
                                                   Recursion

                         Starting Out with Java:
              From Control Structures through Data Structures

                                                  Second Edition

                         by Tony Gaddis and Godfrey Muganda
Chapter Topics
  Chapter 15 discusses the following main topics:
        –    Introduction to Recursion
        –    Solving Problems with Recursion
        –    Examples of Recursive Methods
        –    The Towers of Hanoi




© 2012 Pearson Education, Inc. All rights reserved.   15-2
Introduction to Recursion
 • We have been calling other methods from a
   method.
 • It’s also possible for a method to call itself.
 • A method that calls itself is a recursive method.
 • Example: EndlessRecursion.java




© 2012 Pearson Education, Inc. All rights reserved.    15-3
Introduction to Recursion
  • This method in the example displays the string
    “This is a recursive method.”, and then calls itself.
  • Each time it calls itself, the cycle is repeated
    endlessly.
  • Like a loop, a recursive method must have some
    way to control the number of times it repeats.
  • Example: Recursive.java, RecursionDemo.java




© 2012 Pearson Education, Inc. All rights reserved.         15-4
Introduction to Recursion
      The method is first called
                                                      First call of the method
      from the main method of
      the RecursionDemo                               n=5
      class.                                              Second call of the method
                                                          n=4
      The second through sixth
                                                              Third call of the method
      calls are recursive.
                                                              n=3
                                                                  Fourth call of the method
                                                                  n=2
                                                                       Fifth call of the method
                                                                       n=1
                                                                           Sixth call of the method
                                                                           n=0




© 2012 Pearson Education, Inc. All rights reserved.                                                   15-5
Solving Problems With Recursion
  • Recursion can be a powerful tool for solving
    repetitive problems.
  • Recursion is never absolutely required to solve a
    problem.
  • Any problem that can be solved recursively can also
    be solved iteratively, with a loop.
  • In many cases, recursive algorithms are less efficient
    than iterative algorithms.



© 2012 Pearson Education, Inc. All rights reserved.          15-6
Solving Problems With Recursion
 • Recursive solutions repetitively:
              • allocate memory for parameters and local variables, and
              • store the address of where control returns after the method terminates.
 • These actions are called overhead and take place with
   each method call.
 • This overhead does not occur with a loop.
 • Some repetitive problems are more easily solved with
   recursion than with iteration.
       – Iterative algorithms might execute faster; however,
       – a recursive algorithm might be designed faster.

© 2012 Pearson Education, Inc. All rights reserved.                                   15-7
Solving Problems With Recursion
 • Recursion works like this:
       – A base case is established.
              • If matched, the method solves it and returns.
       – If the base case cannot be solved now:
              • the method reduces it to a smaller problem (recursive case) and calls
                itself to solve the smaller problem.
 • By reducing the problem with each recursive call, the
   base case will eventually be reached and the recursion
   will stop.
 • In mathematics, the notation n! represents the factorial
   of the number n.

© 2012 Pearson Education, Inc. All rights reserved.                                     15-8
Solving Problems With Recursion
 • The factorial of a nonnegative number can be
   defined by the following rules:
       – If n = 0 then n! = 1
       – If n > 0 then n! = 1 × 2 × 3 × ... × n
 • Let’s replace the notation n! with factorial(n),
   which looks a bit more like computer code, and
   rewrite these rules as:
       – If n = 0 then factorial(n) = 1
       – If n > 0 then factorial(n) = 1 × 2 × 3 × ... × n


© 2012 Pearson Education, Inc. All rights reserved.         15-9
Solving Problems With Recursion
  • These rules state that:
        – when n is 0, its factorial is 1, and
        – when n greater than 0, its factorial is the product of all the
          positive integers from 1 up to n.
  • Factorial(6) is calculated as
        – 1 × 2 × 3 × 4 × 5 × 6.
  • The base case is where n is equal to 0:
        if n = 0 then factorial(n) = 1
  • The recursive case, or the part of the problem that we
    use recursion to solve is:
        – if n > 0 then factorial(n) = n × factorial(n – 1)



© 2012 Pearson Education, Inc. All rights reserved.                        15-10
Solving Problems With Recursion
 • The recursive call works on a reduced version of
   the problem, n – 1.
 • The recursive rule for calculating the factorial:
       – If n = 0 then factorial(n) = 1
       – If n > 0 then factorial(n) = n × factorial(n – 1)
 • A Java based solution:
       private static int factorial(int n)
       {
         if (n == 0) return 1; // Base case
         else return n * factorial(n - 1);
       }
 • Example: FactorialDemo.java

© 2012 Pearson Education, Inc. All rights reserved.          15-11
Solving Problems With Recursion
      The method is first called
      from the main method of
                                                      First call of the method
      the FactorialDemo                               n=4
      class.                                          Return value: 24
                                                        Second call of the method
                                                        n=3
                                                        Return value: 6
                                                           Third call of the method
                                                           n=2
                                                           Return value: 2
                                                             Fourth call of the method
                                                             n=1
                                                             Return value: 1
                                                                Fifth call of the method
                                                                n=0
                                                                Return value: 1
© 2012 Pearson Education, Inc. All rights reserved.                                        15-12
Direct and Indirect Recursion
  • When recursive methods directly call themselves it is known as
    direct recursion.
  • Indirect recursion is when method A calls method B, which in
    turn calls method A.
  • There can even be several methods involved in the recursion.
  • Example, method A could call method B, which could call
    method C, which calls method A.
  • Care must be used in indirect recursion to ensure that the proper
    base cases and return values are handled.




© 2012 Pearson Education, Inc. All rights reserved.                 15-13
Summing a Range of Array Elements
  • Recursion can be used to sum a range of array elements.
  • A method, rangeSum takes following arguments:
     – an int array,
     – an int specifying the starting element of the range, and
     – an int specifying the ending element of the range.
     – How it might be called:

               int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
               int sum;
               sum = rangeSum(numbers, 3, 7);




© 2012 Pearson Education, Inc. All rights reserved.               15-14
Summing a Range of Array Elements
 • The definition of the rangeSum method:
       public static int rangeSum(int[] array,
                                  int start, int end)
       {
         if (start > end)
           return 0;
         else
           return array[start]
               + rangeSum(array, start + 1, end);
       }


 • Example: RangeSum.java

© 2012 Pearson Education, Inc. All rights reserved.     15-15
Drawing Concentric Circles
 • The definition of the drawCircles
   method:
       private void drawCircles(Graphics g, int n, int
                                 topXY, intƒsize)
       {
             if (n > 0)
           {
                 g.drawOval(topXY, topXY, size, size);
                 drawCircles(g, n - 1, topXY + 15, size - 30);
           }
         }

 • Example: Circles.java
© 2012 Pearson Education, Inc. All rights reserved.              15-16
The Fibonacci Series
 • Some mathematical problems are designed to be
   solved recursively.
 • One well known example is the calculation of
   Fibonacci numbers.:
       – 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,…
 • After the second number, each number in the series
   is the sum of the two previous numbers.
 • The Fibonacci series can be defined as:
       – F0 = 0
       – F1 = 1
       – FN = FN–1 + FN–2 for N ≥ 2.


© 2012 Pearson Education, Inc. All rights reserved.            15-17
The Fibonacci Series
       public static int fib(int n)
       {
         if (n == 0)
           return 0;
         else if (n == 1)
              return 1;
         else
              return fib(n - 1) + fib(n - 2);
       }
 • This method has two base cases:
       – when n is equal to 0, and
       – when n is equal to 1.
 • Example: FibNumbers.java
© 2012 Pearson Education, Inc. All rights reserved.   15-18
Greatest Common Divisor (GCD)
 • The definition of the gcd method:

       public static int gcd(int x, int y)
       {
            if (x % y == 0)
               return y;
            else
               return gcd(y, x % y);
         }
 • Example: GCDdemo.java

© 2012 Pearson Education, Inc. All rights reserved.   15-19
The Towers of Hanoi
  • The Towers of Hanoi is a mathematical game that
    uses:
        – three pegs and
        – a set of discs with holes through their centers.
  • The discs are stacked on the leftmost peg, in order of
    size with the largest disc at the bottom.
  • The object of the game is to move the pegs from the
    left peg to the right peg by these rules:
        – Only one disk may be moved at a time.
        – A disk cannot be placed on top of a smaller disc.
        – All discs must be stored on a peg except while being moved.


© 2012 Pearson Education, Inc. All rights reserved.                     15-20
The Towers of Hanoi
  • The overall solution to the problem is to move n discs from
    peg 1 to peg 3 using peg 2 as a temporary peg.
  • This algorithm solves the game.
        If n > 0 Then
           Move n – 1 discs from peg A to peg B,
           using peg C as a temporary peg.
           Move the remaining disc from the peg A to peg C.
           Move n – 1 discs from peg B to peg C,
           using peg A as a temporary peg.
        End If
  • The base case for the algorithm is reached when there are no
    more discs to move.
  • Example: Hanoi.java, HanoiDemo.java

© 2012 Pearson Education, Inc. All rights reserved.                15-21

More Related Content

What's hot

Quantifying the call blending balance in two way communication retrial queues...
Quantifying the call blending balance in two way communication retrial queues...Quantifying the call blending balance in two way communication retrial queues...
Quantifying the call blending balance in two way communication retrial queues...wrogiest
 
Stochastic Definite Clause Grammars
Stochastic Definite Clause GrammarsStochastic Definite Clause Grammars
Stochastic Definite Clause GrammarsChristian Have
 
Econometria Jose Nieves
Econometria Jose NievesEconometria Jose Nieves
Econometria Jose Nievespaquitootd
 
Convex optmization in communications
Convex optmization in communicationsConvex optmization in communications
Convex optmization in communicationsDeepshika Reddy
 
Optimization Methods in Finance
Optimization Methods in FinanceOptimization Methods in Finance
Optimization Methods in Financethilankm
 
Mba i ot unit-1.1_linear programming
Mba i ot unit-1.1_linear programmingMba i ot unit-1.1_linear programming
Mba i ot unit-1.1_linear programmingRai University
 
Lp and ip programming cp 9
Lp and ip programming cp 9Lp and ip programming cp 9
Lp and ip programming cp 9M S Prasad
 
C users_mpk7_app_data_local_temp_plugtmp_plugin-week3recursive
C  users_mpk7_app_data_local_temp_plugtmp_plugin-week3recursiveC  users_mpk7_app_data_local_temp_plugtmp_plugin-week3recursive
C users_mpk7_app_data_local_temp_plugtmp_plugin-week3recursiverokiah64
 
Reoptimization Algorithms and Persistent Turing Machines
Reoptimization Algorithms and Persistent Turing MachinesReoptimization Algorithms and Persistent Turing Machines
Reoptimization Algorithms and Persistent Turing MachinesJhoirene Clemente
 
Interval programming
Interval programming Interval programming
Interval programming Zahra Sadeghi
 
Using Alpha-cuts and Constraint Exploration Approach on Quadratic Programming...
Using Alpha-cuts and Constraint Exploration Approach on Quadratic Programming...Using Alpha-cuts and Constraint Exploration Approach on Quadratic Programming...
Using Alpha-cuts and Constraint Exploration Approach on Quadratic Programming...TELKOMNIKA JOURNAL
 
Penalty Function Method For Solving Fuzzy Nonlinear Programming Problem
Penalty Function Method For Solving Fuzzy Nonlinear Programming ProblemPenalty Function Method For Solving Fuzzy Nonlinear Programming Problem
Penalty Function Method For Solving Fuzzy Nonlinear Programming Problempaperpublications3
 

What's hot (19)

Quantifying the call blending balance in two way communication retrial queues...
Quantifying the call blending balance in two way communication retrial queues...Quantifying the call blending balance in two way communication retrial queues...
Quantifying the call blending balance in two way communication retrial queues...
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
 
Stochastic Definite Clause Grammars
Stochastic Definite Clause GrammarsStochastic Definite Clause Grammars
Stochastic Definite Clause Grammars
 
Perceptron
PerceptronPerceptron
Perceptron
 
Econometria Jose Nieves
Econometria Jose NievesEconometria Jose Nieves
Econometria Jose Nieves
 
Convex optmization in communications
Convex optmization in communicationsConvex optmization in communications
Convex optmization in communications
 
Q
QQ
Q
 
Dp
DpDp
Dp
 
Optimization Methods in Finance
Optimization Methods in FinanceOptimization Methods in Finance
Optimization Methods in Finance
 
Boyd 4.6, 4.7
Boyd 4.6, 4.7Boyd 4.6, 4.7
Boyd 4.6, 4.7
 
Mba i ot unit-1.1_linear programming
Mba i ot unit-1.1_linear programmingMba i ot unit-1.1_linear programming
Mba i ot unit-1.1_linear programming
 
Lp and ip programming cp 9
Lp and ip programming cp 9Lp and ip programming cp 9
Lp and ip programming cp 9
 
Unit 2
Unit 2Unit 2
Unit 2
 
C users_mpk7_app_data_local_temp_plugtmp_plugin-week3recursive
C  users_mpk7_app_data_local_temp_plugtmp_plugin-week3recursiveC  users_mpk7_app_data_local_temp_plugtmp_plugin-week3recursive
C users_mpk7_app_data_local_temp_plugtmp_plugin-week3recursive
 
Reoptimization Algorithms and Persistent Turing Machines
Reoptimization Algorithms and Persistent Turing MachinesReoptimization Algorithms and Persistent Turing Machines
Reoptimization Algorithms and Persistent Turing Machines
 
Interval programming
Interval programming Interval programming
Interval programming
 
Using Alpha-cuts and Constraint Exploration Approach on Quadratic Programming...
Using Alpha-cuts and Constraint Exploration Approach on Quadratic Programming...Using Alpha-cuts and Constraint Exploration Approach on Quadratic Programming...
Using Alpha-cuts and Constraint Exploration Approach on Quadratic Programming...
 
presentacion
presentacionpresentacion
presentacion
 
Penalty Function Method For Solving Fuzzy Nonlinear Programming Problem
Penalty Function Method For Solving Fuzzy Nonlinear Programming ProblemPenalty Function Method For Solving Fuzzy Nonlinear Programming Problem
Penalty Function Method For Solving Fuzzy Nonlinear Programming Problem
 

Viewers also liked

Chapter 3 Networking
Chapter 3 NetworkingChapter 3 Networking
Chapter 3 Networkingmlrbrown
 
Networking Chapter 6
Networking Chapter 6Networking Chapter 6
Networking Chapter 6mlrbrown
 
Installing the network
Installing the networkInstalling the network
Installing the networkOnline
 
Hands On Approach To Networking
Hands On Approach To NetworkingHands On Approach To Networking
Hands On Approach To Networkingayanthi
 
Net essentials6e ch4
Net essentials6e ch4Net essentials6e ch4
Net essentials6e ch4APSU
 
Chapter 2 Networking
Chapter 2 NetworkingChapter 2 Networking
Chapter 2 Networkingmlrbrown
 
Networking Chapter 10
Networking Chapter 10Networking Chapter 10
Networking Chapter 10mlrbrown
 
Networking Chapter 4
Networking Chapter 4Networking Chapter 4
Networking Chapter 4mlrbrown
 
Networking Chapter 5
Networking Chapter 5Networking Chapter 5
Networking Chapter 5mlrbrown
 
Networking Chapter 8
Networking Chapter 8Networking Chapter 8
Networking Chapter 8mlrbrown
 
Networking Chapter 13
Networking Chapter 13Networking Chapter 13
Networking Chapter 13mlrbrown
 
Chapter 1 Networking
Chapter 1 NetworkingChapter 1 Networking
Chapter 1 Networkingmlrbrown
 
OpenStack Neutron Tutorial
OpenStack Neutron TutorialOpenStack Neutron Tutorial
OpenStack Neutron Tutorialmestery
 

Viewers also liked (15)

Chapter 3 Networking
Chapter 3 NetworkingChapter 3 Networking
Chapter 3 Networking
 
Networking Chapter 6
Networking Chapter 6Networking Chapter 6
Networking Chapter 6
 
Installing the network
Installing the networkInstalling the network
Installing the network
 
Hands On Approach To Networking
Hands On Approach To NetworkingHands On Approach To Networking
Hands On Approach To Networking
 
Net essentials6e ch4
Net essentials6e ch4Net essentials6e ch4
Net essentials6e ch4
 
Chapter 2 Networking
Chapter 2 NetworkingChapter 2 Networking
Chapter 2 Networking
 
Networking Chapter 10
Networking Chapter 10Networking Chapter 10
Networking Chapter 10
 
Networking Chapter 4
Networking Chapter 4Networking Chapter 4
Networking Chapter 4
 
Networking Chapter 5
Networking Chapter 5Networking Chapter 5
Networking Chapter 5
 
Networking Chapter 8
Networking Chapter 8Networking Chapter 8
Networking Chapter 8
 
Networking Chapter 13
Networking Chapter 13Networking Chapter 13
Networking Chapter 13
 
Chapter 1 Networking
Chapter 1 NetworkingChapter 1 Networking
Chapter 1 Networking
 
CCNA TCP/IP
CCNA TCP/IPCCNA TCP/IP
CCNA TCP/IP
 
OpenStack Neutron Tutorial
OpenStack Neutron TutorialOpenStack Neutron Tutorial
OpenStack Neutron Tutorial
 
Networking ppt
Networking ppt Networking ppt
Networking ppt
 

Similar to Cso gaddis java_chapter15

ch08 modified.pptmodified.pptmodified.ppt
ch08 modified.pptmodified.pptmodified.pptch08 modified.pptmodified.pptmodified.ppt
ch08 modified.pptmodified.pptmodified.ppttahirnaquash2
 
Recursion.pptx
Recursion.pptxRecursion.pptx
Recursion.pptxVijalJain3
 
Lecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesLecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesjayavignesh86
 
Recursion | C++ | DSA
Recursion | C++ | DSARecursion | C++ | DSA
Recursion | C++ | DSASumit Pandey
 

Similar to Cso gaddis java_chapter15 (11)

algo_vc_lecture8.ppt
algo_vc_lecture8.pptalgo_vc_lecture8.ppt
algo_vc_lecture8.ppt
 
ch08 modified.pptmodified.pptmodified.ppt
ch08 modified.pptmodified.pptmodified.pptch08 modified.pptmodified.pptmodified.ppt
ch08 modified.pptmodified.pptmodified.ppt
 
Ch08
Ch08Ch08
Ch08
 
Recursion.pptx
Recursion.pptxRecursion.pptx
Recursion.pptx
 
Ch08
Ch08Ch08
Ch08
 
DS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and ConquerDS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and Conquer
 
Daa notes 2
Daa notes 2Daa notes 2
Daa notes 2
 
Lecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesLecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrences
 
Icom4015 lecture12-s16
Icom4015 lecture12-s16Icom4015 lecture12-s16
Icom4015 lecture12-s16
 
Recursion | C++ | DSA
Recursion | C++ | DSARecursion | C++ | DSA
Recursion | C++ | DSA
 
Mc0063(a) unit4-fi
Mc0063(a) unit4-fiMc0063(a) unit4-fi
Mc0063(a) unit4-fi
 

More from mlrbrown

Cso gaddis java_chapter14
Cso gaddis java_chapter14Cso gaddis java_chapter14
Cso gaddis java_chapter14mlrbrown
 
Cso gaddis java_chapter13
Cso gaddis java_chapter13Cso gaddis java_chapter13
Cso gaddis java_chapter13mlrbrown
 
Cso gaddis java_chapter12
Cso gaddis java_chapter12Cso gaddis java_chapter12
Cso gaddis java_chapter12mlrbrown
 
Cso gaddis java_chapter11
Cso gaddis java_chapter11Cso gaddis java_chapter11
Cso gaddis java_chapter11mlrbrown
 
Cso gaddis java_chapter10
Cso gaddis java_chapter10Cso gaddis java_chapter10
Cso gaddis java_chapter10mlrbrown
 
Cso gaddis java_chapter9ppt
Cso gaddis java_chapter9pptCso gaddis java_chapter9ppt
Cso gaddis java_chapter9pptmlrbrown
 
Cso gaddis java_chapter8
Cso gaddis java_chapter8Cso gaddis java_chapter8
Cso gaddis java_chapter8mlrbrown
 
Cso gaddis java_chapter7
Cso gaddis java_chapter7Cso gaddis java_chapter7
Cso gaddis java_chapter7mlrbrown
 
Cso gaddis java_chapter6
Cso gaddis java_chapter6Cso gaddis java_chapter6
Cso gaddis java_chapter6mlrbrown
 
Cso gaddis java_chapter5
Cso gaddis java_chapter5Cso gaddis java_chapter5
Cso gaddis java_chapter5mlrbrown
 
Cso gaddis java_chapter4
Cso gaddis java_chapter4Cso gaddis java_chapter4
Cso gaddis java_chapter4mlrbrown
 
Cso gaddis java_chapter3
Cso gaddis java_chapter3Cso gaddis java_chapter3
Cso gaddis java_chapter3mlrbrown
 
Cso gaddis java_chapter2
Cso gaddis java_chapter2Cso gaddis java_chapter2
Cso gaddis java_chapter2mlrbrown
 
Cso gaddis java_chapter1
Cso gaddis java_chapter1Cso gaddis java_chapter1
Cso gaddis java_chapter1mlrbrown
 
Networking Chapter 16
Networking Chapter 16Networking Chapter 16
Networking Chapter 16mlrbrown
 
Networking Chapter 15
Networking Chapter 15Networking Chapter 15
Networking Chapter 15mlrbrown
 
Networking Chapter 14
Networking Chapter 14Networking Chapter 14
Networking Chapter 14mlrbrown
 
Networking Chapter 12
Networking Chapter 12Networking Chapter 12
Networking Chapter 12mlrbrown
 
Networking Chapter 11
Networking Chapter 11Networking Chapter 11
Networking Chapter 11mlrbrown
 
Networking Chapter 9
Networking Chapter 9Networking Chapter 9
Networking Chapter 9mlrbrown
 

More from mlrbrown (20)

Cso gaddis java_chapter14
Cso gaddis java_chapter14Cso gaddis java_chapter14
Cso gaddis java_chapter14
 
Cso gaddis java_chapter13
Cso gaddis java_chapter13Cso gaddis java_chapter13
Cso gaddis java_chapter13
 
Cso gaddis java_chapter12
Cso gaddis java_chapter12Cso gaddis java_chapter12
Cso gaddis java_chapter12
 
Cso gaddis java_chapter11
Cso gaddis java_chapter11Cso gaddis java_chapter11
Cso gaddis java_chapter11
 
Cso gaddis java_chapter10
Cso gaddis java_chapter10Cso gaddis java_chapter10
Cso gaddis java_chapter10
 
Cso gaddis java_chapter9ppt
Cso gaddis java_chapter9pptCso gaddis java_chapter9ppt
Cso gaddis java_chapter9ppt
 
Cso gaddis java_chapter8
Cso gaddis java_chapter8Cso gaddis java_chapter8
Cso gaddis java_chapter8
 
Cso gaddis java_chapter7
Cso gaddis java_chapter7Cso gaddis java_chapter7
Cso gaddis java_chapter7
 
Cso gaddis java_chapter6
Cso gaddis java_chapter6Cso gaddis java_chapter6
Cso gaddis java_chapter6
 
Cso gaddis java_chapter5
Cso gaddis java_chapter5Cso gaddis java_chapter5
Cso gaddis java_chapter5
 
Cso gaddis java_chapter4
Cso gaddis java_chapter4Cso gaddis java_chapter4
Cso gaddis java_chapter4
 
Cso gaddis java_chapter3
Cso gaddis java_chapter3Cso gaddis java_chapter3
Cso gaddis java_chapter3
 
Cso gaddis java_chapter2
Cso gaddis java_chapter2Cso gaddis java_chapter2
Cso gaddis java_chapter2
 
Cso gaddis java_chapter1
Cso gaddis java_chapter1Cso gaddis java_chapter1
Cso gaddis java_chapter1
 
Networking Chapter 16
Networking Chapter 16Networking Chapter 16
Networking Chapter 16
 
Networking Chapter 15
Networking Chapter 15Networking Chapter 15
Networking Chapter 15
 
Networking Chapter 14
Networking Chapter 14Networking Chapter 14
Networking Chapter 14
 
Networking Chapter 12
Networking Chapter 12Networking Chapter 12
Networking Chapter 12
 
Networking Chapter 11
Networking Chapter 11Networking Chapter 11
Networking Chapter 11
 
Networking Chapter 9
Networking Chapter 9Networking Chapter 9
Networking Chapter 9
 

Recently uploaded

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Cso gaddis java_chapter15

  • 1. © 2012 Pearson Education, Inc. All rights reserved. Chapter 15: Recursion Starting Out with Java: From Control Structures through Data Structures Second Edition by Tony Gaddis and Godfrey Muganda
  • 2. Chapter Topics Chapter 15 discusses the following main topics: – Introduction to Recursion – Solving Problems with Recursion – Examples of Recursive Methods – The Towers of Hanoi © 2012 Pearson Education, Inc. All rights reserved. 15-2
  • 3. Introduction to Recursion • We have been calling other methods from a method. • It’s also possible for a method to call itself. • A method that calls itself is a recursive method. • Example: EndlessRecursion.java © 2012 Pearson Education, Inc. All rights reserved. 15-3
  • 4. Introduction to Recursion • This method in the example displays the string “This is a recursive method.”, and then calls itself. • Each time it calls itself, the cycle is repeated endlessly. • Like a loop, a recursive method must have some way to control the number of times it repeats. • Example: Recursive.java, RecursionDemo.java © 2012 Pearson Education, Inc. All rights reserved. 15-4
  • 5. Introduction to Recursion The method is first called First call of the method from the main method of the RecursionDemo n=5 class. Second call of the method n=4 The second through sixth Third call of the method calls are recursive. n=3 Fourth call of the method n=2 Fifth call of the method n=1 Sixth call of the method n=0 © 2012 Pearson Education, Inc. All rights reserved. 15-5
  • 6. Solving Problems With Recursion • Recursion can be a powerful tool for solving repetitive problems. • Recursion is never absolutely required to solve a problem. • Any problem that can be solved recursively can also be solved iteratively, with a loop. • In many cases, recursive algorithms are less efficient than iterative algorithms. © 2012 Pearson Education, Inc. All rights reserved. 15-6
  • 7. Solving Problems With Recursion • Recursive solutions repetitively: • allocate memory for parameters and local variables, and • store the address of where control returns after the method terminates. • These actions are called overhead and take place with each method call. • This overhead does not occur with a loop. • Some repetitive problems are more easily solved with recursion than with iteration. – Iterative algorithms might execute faster; however, – a recursive algorithm might be designed faster. © 2012 Pearson Education, Inc. All rights reserved. 15-7
  • 8. Solving Problems With Recursion • Recursion works like this: – A base case is established. • If matched, the method solves it and returns. – If the base case cannot be solved now: • the method reduces it to a smaller problem (recursive case) and calls itself to solve the smaller problem. • By reducing the problem with each recursive call, the base case will eventually be reached and the recursion will stop. • In mathematics, the notation n! represents the factorial of the number n. © 2012 Pearson Education, Inc. All rights reserved. 15-8
  • 9. Solving Problems With Recursion • The factorial of a nonnegative number can be defined by the following rules: – If n = 0 then n! = 1 – If n > 0 then n! = 1 × 2 × 3 × ... × n • Let’s replace the notation n! with factorial(n), which looks a bit more like computer code, and rewrite these rules as: – If n = 0 then factorial(n) = 1 – If n > 0 then factorial(n) = 1 × 2 × 3 × ... × n © 2012 Pearson Education, Inc. All rights reserved. 15-9
  • 10. Solving Problems With Recursion • These rules state that: – when n is 0, its factorial is 1, and – when n greater than 0, its factorial is the product of all the positive integers from 1 up to n. • Factorial(6) is calculated as – 1 × 2 × 3 × 4 × 5 × 6. • The base case is where n is equal to 0: if n = 0 then factorial(n) = 1 • The recursive case, or the part of the problem that we use recursion to solve is: – if n > 0 then factorial(n) = n × factorial(n – 1) © 2012 Pearson Education, Inc. All rights reserved. 15-10
  • 11. Solving Problems With Recursion • The recursive call works on a reduced version of the problem, n – 1. • The recursive rule for calculating the factorial: – If n = 0 then factorial(n) = 1 – If n > 0 then factorial(n) = n × factorial(n – 1) • A Java based solution: private static int factorial(int n) { if (n == 0) return 1; // Base case else return n * factorial(n - 1); } • Example: FactorialDemo.java © 2012 Pearson Education, Inc. All rights reserved. 15-11
  • 12. Solving Problems With Recursion The method is first called from the main method of First call of the method the FactorialDemo n=4 class. Return value: 24 Second call of the method n=3 Return value: 6 Third call of the method n=2 Return value: 2 Fourth call of the method n=1 Return value: 1 Fifth call of the method n=0 Return value: 1 © 2012 Pearson Education, Inc. All rights reserved. 15-12
  • 13. Direct and Indirect Recursion • When recursive methods directly call themselves it is known as direct recursion. • Indirect recursion is when method A calls method B, which in turn calls method A. • There can even be several methods involved in the recursion. • Example, method A could call method B, which could call method C, which calls method A. • Care must be used in indirect recursion to ensure that the proper base cases and return values are handled. © 2012 Pearson Education, Inc. All rights reserved. 15-13
  • 14. Summing a Range of Array Elements • Recursion can be used to sum a range of array elements. • A method, rangeSum takes following arguments: – an int array, – an int specifying the starting element of the range, and – an int specifying the ending element of the range. – How it might be called: int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int sum; sum = rangeSum(numbers, 3, 7); © 2012 Pearson Education, Inc. All rights reserved. 15-14
  • 15. Summing a Range of Array Elements • The definition of the rangeSum method: public static int rangeSum(int[] array, int start, int end) { if (start > end) return 0; else return array[start] + rangeSum(array, start + 1, end); } • Example: RangeSum.java © 2012 Pearson Education, Inc. All rights reserved. 15-15
  • 16. Drawing Concentric Circles • The definition of the drawCircles method: private void drawCircles(Graphics g, int n, int topXY, intƒsize) { if (n > 0) { g.drawOval(topXY, topXY, size, size); drawCircles(g, n - 1, topXY + 15, size - 30); } } • Example: Circles.java © 2012 Pearson Education, Inc. All rights reserved. 15-16
  • 17. The Fibonacci Series • Some mathematical problems are designed to be solved recursively. • One well known example is the calculation of Fibonacci numbers.: – 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,… • After the second number, each number in the series is the sum of the two previous numbers. • The Fibonacci series can be defined as: – F0 = 0 – F1 = 1 – FN = FN–1 + FN–2 for N ≥ 2. © 2012 Pearson Education, Inc. All rights reserved. 15-17
  • 18. The Fibonacci Series public static int fib(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return fib(n - 1) + fib(n - 2); } • This method has two base cases: – when n is equal to 0, and – when n is equal to 1. • Example: FibNumbers.java © 2012 Pearson Education, Inc. All rights reserved. 15-18
  • 19. Greatest Common Divisor (GCD) • The definition of the gcd method: public static int gcd(int x, int y) { if (x % y == 0) return y; else return gcd(y, x % y); } • Example: GCDdemo.java © 2012 Pearson Education, Inc. All rights reserved. 15-19
  • 20. The Towers of Hanoi • The Towers of Hanoi is a mathematical game that uses: – three pegs and – a set of discs with holes through their centers. • The discs are stacked on the leftmost peg, in order of size with the largest disc at the bottom. • The object of the game is to move the pegs from the left peg to the right peg by these rules: – Only one disk may be moved at a time. – A disk cannot be placed on top of a smaller disc. – All discs must be stored on a peg except while being moved. © 2012 Pearson Education, Inc. All rights reserved. 15-20
  • 21. The Towers of Hanoi • The overall solution to the problem is to move n discs from peg 1 to peg 3 using peg 2 as a temporary peg. • This algorithm solves the game. If n > 0 Then Move n – 1 discs from peg A to peg B, using peg C as a temporary peg. Move the remaining disc from the peg A to peg C. Move n – 1 discs from peg B to peg C, using peg A as a temporary peg. End If • The base case for the algorithm is reached when there are no more discs to move. • Example: Hanoi.java, HanoiDemo.java © 2012 Pearson Education, Inc. All rights reserved. 15-21