Recursion in Java The answer to life’s greatest mysteries are on the last slide.

Slides:



Advertisements
Similar presentations
Introduction to Recursion and Recursive Algorithms
Advertisements

Procedural programming in Java
Factorial Recursion stack Binary Search Towers of Hanoi
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 12: Recursion.
Recursion Definition: A method that calls itself. Recursion can be direct or indirect. Indirect recursion involves a method call that eventually recalls.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 19 Recursion.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 12: Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L10 (Chapter 19) Recursion.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Recursion.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
CMSC 2021 Recursion Recursive Definition – one that defines something in terms of itself Recursion – A technique that allows us to break down a problem.
Chapter 14: Recursion J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second Edition.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1Recursion. 2 Outline thinking recursively recursive algorithms iteration vs. recursion recursive functions integer exponentiation (pow) infinite recursion.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Chapter 14 Recursion. Chapter Objectives Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Chapter 13 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Recursive Functions for Tasks(13.1) Recursive Functions.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 14 Recursion.
CSE 501N Fall ‘09 12: Recursion and Recursive Algorithms 8 October 2009 Nick Leidenfrost.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
IB Computer Science Unit 5 – Advanced Topics Recursion.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 13 Recursion.
Building Java Programs Chapter 12 Recursion Copyright (c) Pearson All rights reserved.
1 Recursion n what is it? n how to build recursive algorithms n recursion analysis n tracing simple recursive functions n hands on attempts at writing.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
Program Development and Design Using C++, Third Edition
Chapter 6 (Lafore’s Book) Recursion Hwajung Lee.  Definition: An algorithmic technique. To solve a problem on an instance of size n, the instance is:
Welcome to Recursion! Say what?!? Recursion is… the process of solving large problems by simplifying them into smaller ones. similar to processing using.
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
Lecture 24: Recursion Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
4. Java language basics: Function
Topic 6 Recursion.
Recursion what is it? how to build recursive algorithms
Recursion DRILL: Please take out your notes on Recursion
Recursion A problem solving technique where an algorithm is defined in terms of itself A recursive method is a method that calls itself A recursive algorithm.
Java Software Structures: John Lewis & Joseph Chase
Announcements Final Exam on August 17th Wednesday at 16:00.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Stacks & Recursion.
Chapter 8: Recursion Java Software Solutions
Recursion.
Recursion Chapter 18.
slides created by Marty Stepp and Alyssa Harding
Recursion Definition: A method that calls itself. Examples
Lecture 19: Recursion Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
ITEC324 Principle of CS III
Presentation transcript:

Recursion in Java The answer to life’s greatest mysteries are on the last slide

Recursion  Recursion is a technique widely used in programming  In fact some programming languages have no loops, only recursion  Recursion is a key element to advanced studies such as computational intelligence  Beginning programmers usually groan at recursion… real programmers love it!

Recursion in Java  A method is recursive if it calls itself.  There are two key things in recursion  Base step: ends the recursion  Recursive step: breaks down the problem to smaller sub problems  Before you code anything, you need to find those two steps… otherwise you may not understand the problem properly

Example  Here is a simple recursive java function for called countdown: public void countDown( int value ) { if( value == 0 ) System.out.println( “Blast Off!!!” );//base case, no recursion else{ System.out.println( value ); countDown( value – 1);//recursive call of small problem }} LETS TRACE countDown( 5 ) BY HAND

Why Recursion?  Fact: All recursion can be re written as a non recursive form with a loop  Some algorithms are exceedingly complex as a loop, yet very elegant in a recursive form.  Easier to understand  less “bugs” = better programs  Let’s take a look at Paint for a minute…

The Flood Fill Algorithm  The recursion is tricky to follow, but look at how simple the code is! public void floodFill( int x, int y, Colour clicked, Colour change ) { if( outOfBounds(x,y) || getColour(x,y) == change || getColour(x,y) != clicked ) return;//nothing to do – base case setColour(x,y,change);//colour is the same as was clicked, change it //Recursive call on neighbours floodFill( x + 1, y, clicked, colour ); floodFill( x, y + 1, clicked, colour ); floodFill( x - 1, y, clicked, colour ); floodFill( x, y - 1, clicked, colour ); }

Getting the hang of it?  Let’s try a couple together  Base step  Recursive step  Sum of n numbers  Ex = 15  Factorials  0! = 1  3! = 3 x 2 x 1 = 3 x 2!  100! = 100x99x98x..x3x2x1 = 100 x 99!

Still Need Practice?  Here are two other famous recursive examples:  Fibonacci numbers  1 st number is 1, 2 nd number is 1  Every number after 2 is the sum of the previous two: 1,1,2,3,5,8,13,…  Euclid’s GCF (from ~300BC)   Take the larger of the two and divide it by the smaller  If the remainder is zero, return the smaller number  Otherwise take the GCF of smaller and remainder  Example let’s try 60 and 105

Pascal’s Triangle …

Pascal’s Triangle Cont’  What’s the recursive pattern in Pascal’s triangle?  Hint: Number each row and column  What is/are the base case(s)?  What is the recursive case?

Performance: Loops vs. Recursion  Why not always use recursion if it makes our code easier to understand?  The key reason is performance  Recursion can quickly overflow the computer’s memory  Each method call has its own “stack” in memory when it is called (holds variables, loops, etc.)  When you make a recursive call, another copy of the method is stored in memory to preserve the state when it returns.  With loops, the variables are reused  Last I had heard, Sun’s java compiler will translate tail recursion into a loop for you  Tail recursion means the recursive call is the last piece of code in the method (nothing is computed after it returns)

Recursion in Memory  Consider a call to factorial( 3 ):  factorial(3)  3 * factorial(2)  2 * factorial(1)  2 * factorial(1)  1 * factorial(0) 1 Recursion ends, return to last caller: 1 * 1 = 1  2 * 1 = 2  3 * 2 = 6

Recursion in Memory  With a loop it would look like this: public int factorial( int n ) { int fac = 1; for( int counter = 2; counter <= n; counter++ ) fac *= counter; return fac; } A call to factorial( 3 ) is now just: 1 * 2 * 3 = 6

The H-Fractal  I’ll code a fractal with you so you can see just how powerful recursion is for problem solving  It would probably take me all day to code this with a loop  I can do it with recursion in about 5 minutes

Exercises  Create a recursive method to calculate the sum of squares:  For example, sumSquares( 3 )  Is = 14

Exercises  Create a recursive method to calculate positive integer exponents  Ex.  findExponent( 3, 2 )  Returns 9

Exercises  Create a recursive method to determine if the values in an array are increasing  You need an extra parameter telling you which index to start testing from  isIncr( int[] data, int start )  isIncr( {1,3,5,9},0 ) returns true  isIncr( {3,1,2,4},0 ) returns false

Exercises  Create a recursive method to sum the values in an array:  sum( int[] data, int start )  sum( {4,2,5}, 0 )  Returns 11

Exercises  Create a recursive method called reverse that reverses the elements in an array  Reverse( int[] data )  Reverse( {1,3,5,2,7 } )  {7,2,5,3,1}

Exercises – Reverse Cont’  Sometimes when we are using recursion, we will write a helper method to hold more parameters.  In the previous example to reverse an array you should write a helper method called:  ReverseHelper( int[] data, int start, int end )  When you call Reverse( int[] data ) use the helper method as follows (it does all the work)  ReverseHelper( data, 0, data.length)

Exercises  Create a recursive method to determine whether or not a word is a palindrome or not.  A palindrome is a word spelled the same forwards and backwards  For example Ogopogo  public boolean isPalidrome(String word)

Exercises  To convert an integer to base 2 (binary) here is an algorithm:  public String toBinary( int n )  If the number is zero, return 0  Otherwise,  Compute the quotient and remainder when dividing by 2  The binary value of the number given is the binary value of the quotient followed by the remainder

Binary Numbers  Ex. Binary value of 13: CalculationQuotientRemainder 13/261 6/230 3/211 1/201 0return 0 13 = in binary

Bonus Graphics - Fractals  Three fractals which can be created using recursion are:  Sierpinski’s Gasket  Koch’s Snowflake  Dragon Fractal  Create a recursive graphics program to display any of these fractals at a given level  Demo will be done in class for each fractal and how they can be obtained

Life’s Greatest Mysteries Revealed!  The answer to life’s greatest mysteries are on the first slide