CS180 RECURSION March 28,2008. Announcements Project 7 : Recursive Expression Evaluators Milestone Due : 4/2/2008 Project Due : 4/9/2008 Exam 2 to be.

Slides:



Advertisements
Similar presentations
1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Advertisements

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.
Recursion. Binary search example postponed to end of lecture.
Recursion Chapter 11 Chapter 11.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Slides prepared by Rose Williams, Binghamton University Chapter 11 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.
Programming with Recursion
Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
1 Chapter 7 Recursion. 2 What Is Recursion? l Recursive call A method call in which the method being called is the same as the one making the call l Direct.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Unit 181 Recursion Definition Recursive Methods Constructing Recursion Benefits and Usage Infinite Recursion Recursion Removal Examples Exercises.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
M180: Data Structures & Algorithms in Java
Chapter 12 Recursion, Complexity, and Searching and Sorting
Recursion Chapter 11. The Basics of Recursion: Outline Introduction to Recursion How Recursion Works Recursion versus Iteration Recursive Methods That.
1 Programming with Recursion. 2 Recursive Function Call A recursive call is a function call in which the called function is the same as the one making.
Recursion Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
10/14/2015cosc237/recursion1 Recursion A method of defining a concept which refers to the concept itself A method of solving a problem by reducing it to.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County.
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.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
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.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Chapter 6 Recursion. Solving simple problems Iteration can be replaced by a recursive function Recursion is the process of a function calling itself.
Chapter 7 Programming with Recursion. What Is Recursion? Recursive call A method call in which the method being called is the same as the one.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Chapter 111 Recursion Chapter Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
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.
CS 100Lecture 231 Announcements Check your grades on the door of 5141 Upson More review tomorrow Review session Sunday night w/Alan FINAL EXAM: Tuesday.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Data Structures I (CPCS-204) Week # 5: Recursion Dr. Omar Batarfi Dr. Yahya Dahab Dr. Imtiaz Khan.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Recursion Powerful Tool
Chapter 15 Recursion.
Chapter 15 Recursion.
Java Software Structures: John Lewis & Joseph Chase
Chapter 14 Recursion. Chapter 14 Recursion Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively.
Programming with Recursion
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Chapter 12 Recursion (methods calling themselves)
The Basics of Recursion
Recursion Chapter 11.
Basics of Recursion Programming with Recursion
Recursion Chapter 11.
The structure of programming
Recursion Method calling itself (circular definition)
Presentation transcript:

CS180 RECURSION March 28,2008

Announcements Project 7 : Recursive Expression Evaluators Milestone Due : 4/2/2008 Project Due : 4/9/2008 Exam 2 to be handed out. Exam 2 grades are available on blackboard. Exam 2 key has been posted on the course website.

What is Recursion? Calling of a method from within the definition of the same method. -known as recursive call, or recursive invocation. e.g. factorial(n) = n*factorial(n-1); Recursion improves clarity of the program. Suitable to problems that can be solved by solving a smaller version of itself. Recursive calls may or may not return a value.

Recursion Guidelines The method definition can be a branching statement leading to different cases based on some parameter being supplied. One or more of them generally work on smaller sections of the task to be performed. This involves a recursive call to the same function. One or more of them should have no recursive calls and should ensure termination of the recursive flow. These branches are known as stopping cases or base cases.

Simple Example: Sum of first ‘n’ natural numbers Class MySum { public static void main(String args[])‏ { MySum s = new MySum(); int n = 6; System.out.println(“Sum of “+n+” numbers is “+s.nsum(n)); } public int nsum(int n)‏ { if (n == 1) return 1; // Stopping condition else return n + nsum(n-1); // Recursive call to smaller problem }

Working of Recursion.. nsum(6) nsum(5) nsum(4) nsum(3) nsum(2) nsum(1)2 + 1 Stopping condition at n = 1. Calls Evaluations

More examples 1) public static void inWords(int number){ if (number < 10) print(digitWord(number)+” “); else { inWords(number/10);  Stmt 1 print(digitWord(number%10) + “ “);  Stmt 2 } What if Stmt 1 and Stmt 2 are in the reverse order ? 2) Revisiting the quiz in class: (No for/while loops, just if-else needed)‏ Method returns true if a[i]==b[i] ….. a[n] == b[n] ; false otherwise public boolean same(int a[],int b[], int i, int n) { if (i==n)‏ return (a[i] == b[i]); else return (a[i] == b[i]) && same(a,b,i+1,n); }

More examples A =2 1 2 det(A) = 1(1*1-1*2) - 2(2*1-3*2) + 3(2*1-3*1)‏ = 4 Smaller matrix is obtained by removing i th row and the j th column where the circled number is A i,j Circled numbers should belong to a single row / column. Can be extended to any NxN matrix. Pseudo code: (iteration + recursion)‏ if (size is 2x2 ) return (ad-bc); else (-1) 1+1 A 1,1 *det(mA 1,1 ) + (-1) 1+2 A 1,2 *det(mA 1,2 ) + ….. (-1) 1+n A 1,n *det(mA 1,n ) det(smaller matrix) ‏

Recursion vs Iteration Cons: Recursion in general is less efficient than iteration. More complicated as we need to keep track of the recursive calls and suspended computations to debug the flow. Pros: Better expresses the intent of the program. In most cases, shorter and easier to write when compared to the corresponding iterative definition.

Infinite recursion If the recursive call does not solve a smaller/simpler version of the problem, a base case may never be reached. This leads to the method calling itself repeatedly. (Eventually results in a stack overflow.)‏ This is known as Infinite Recursion. int factorial(int n)‏ { // Base condition missing. When would this stop ? return n* factorial(n-1); }

Binary Search Linear search in a sorted array : for (int i=0;i< arr.length;i++)‏ if (arr[i] == num) return num; What if the number we are looking for is the last number on the array? Use binary search for sorted arrays. Quicker !

Binary Search contd.. Search using recursion: mid = (first + last)/2 if (first > last)‏ return -1; else if (target == a[mid])‏ return mid; else if (target < a[mid] search a[first] through a[mid-1] else search a[mid + 1] through a[last] Size of array to be searched reduced to about half the size in each call. Note: No suspended computation to track as in previous examples (factorial, sum of n numbers etc.,)‏

Merge Sort Algorithm: If the array has only one element, do nothing. Copy the first half of the elements into an array named front. Copy the second half of the elements into an array named tail. Sort array front recursively. Sort array tail recursively. Merge arrays front and tail.

Merge sort

Exam 2 Questions 2) System.out.println - example for Overloading Recall println takes in arguments of various data types. 3) import and package : import univ.* does not import classes in sub-directories like univ.people etc., import univ.*.* invalid. package univ.* invalid.

Exam 2 Questions 9) Class not commonly used in reading text file – ObjectInputStream. Recall its usage in reading binary files. 11) public class Sta { private static double d = 0; // shared copy private double e = 0; // instance variable public Sta () { ++d ; ++e; } public static void main(String [] args) { Sta s1 = new Sta();  d is 1, e is 1 Sta s2 = new Sta();  d is 2, e is 1 double r = d + s1.e + s2.e; } r = 4.0

Exam 2 Questions 13) Points to remember: * Cannot instantiate interfaces, abstract classes * An instance of a class can be assigned to a reference variable of a class/interface above this class in the hierarchy. 14) B extends A A aObj = … B bObj = (B) aObj; * B comes below A in the hierarchy. Hence reference variable of type B holding an instance of A may not be safe. * Resolved at runtime. Why not compile time? (What if A aObj = new B() )‏

Exam 2 Questions 16)‏ public class A{ private int i = 1; public int getI (){ return I; } } public class B extends A { private int i; public B (int i)‏ { this.i = I; } public int sum (A a) { return (i + getI() + a.getI()); } public static void main (String[] args){ B b = new B(2); int result = b.sum(b); } Result is 4 Note that there is no getI() in B ; inherited from A. Suppose i is public, are a.i and i in the method sum same??

Exam 2 Questions 20) public class A{ public static void f(int[] arr){ for (int k=0; k<arr.length; k++)‏ arr[k] = arr[k] * arr[k]; } public static void g(int[] arr, int x){ int[] temp = arr; arr = new int[temp.length * x]; for (int k=0; k<arr.length; k++)‏ arr[k] = temp[k % temp.length]; } public static void main(String[] args){ int[] arr = {1, 2, 3, 4, 5}; f(arr); ----  arr = { 1,4,9,16,25} g(arr, 2); ---  arr = { 1,4,9,16,25} -- ? for (int k=0; k<arr.length; k++)‏ System.out.print(arr[k] + " "); } arr here is not same as the arr passed from main. It is a reference to the same location as the ‘arr’ in main. This statement changes its reference to a different location. Hence, we can stop worrying about any modifications from this point.

Project 7 Polish notation : / * + 8 #1 -7 #5 #1: #5: * 3 -4 Parsed into a HashMap: Key Value * 3 -4 Value of above expression : (Use recursion)‏ / * + 8 (3) -7 (-12) = / * (11) -7 (-12) = / = 6 /,*,+, Token Type : OP (operator)‏ 1,3,-5 … --- Token Type : INT (integer)‏ #4, #57 …. --- Token Type : LABEL ( value to be returned is the corresponding expression)‏

Quiz Write a program to find the number of prime numbers between two positive integers n 1 and n 2 (inclusive) using recursion. Assume you already have a boolean function isPrime(n) provided.