COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Similar documents
COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems. COMP Week 8 & 9 1

Recursive Thinking. Chapter 8: Recursion. Recursive Definitions. Recursion. Java Software Solutions for AP* Computer Science A 2nd Edition

Recursion -- Introduction

Recursive Definitions

Lecture 5: Methods CS2301

Loops. CSE 114, Computer Science 1 Stony Brook University

CS1150 Principles of Computer Science Methods

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

CS1150 Principles of Computer Science Methods

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Lecture 6: Recursion RECURSION

CS111: PROGRAMMING LANGUAGE II

Fundamentals of Programming Session 13

Recursion. Chapter Simple Recursion. Goals Trace recursive algorithms Implement recursive algorithms

Controls Structure for Repetition

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

CMPT 125: Lecture 4 Conditionals and Loops

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Linked List Implementation of Queues

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

Programming II (CS300)

Fun facts about recursion

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Recursion. Comp Sci 1575 Data Structures. Introduction. Simple examples. The call stack. Types of recursion. Recursive programming

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

University of Palestine. Mid Exam Total Grade: 100

Chapter 12 Supplement: Recursion with Java 1.5. Mr. Dave Clausen La Cañada High School

Programming II (CS300)

Introduction to Programming (Java) 4/12

Methods. CSE 114, Computer Science 1 Stony Brook University

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Reduction & Recursion Overview

Lecture 7 CS2110 Fall 2014 RECURSION

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Recursion. Fundamentals of Computer Science

CS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions:

Programming II (CS300)

CS 11 java track: lecture 1

Functions BCA-105. Few Facts About Functions:

User Defined Functions

CSC 2400: Computer Systems. Using the Stack for Function Calls

Subprograms, Subroutines, and Functions

COS 126 General Computer Science Spring Written Exam 1

C22a: Problem Solving using Recursion

COMP-202: Foundations of Programming

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

Lecture 6 CS2110 Spring 2013 RECURSION

LAB C Translating Utility Classes

Introduction to the Java Basics: Control Flow Statements

CT 229 Methods Continued

CS171:Introduction to Computer Science II

Computer Science E-119 Fall Problem Set 1. Due before lecture on Wednesday, September 26

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Recursion. Let s start by looking at some problems that are nicely solved using recursion. First, let s look at generating The Fibonacci series.

Java Coding 3. Over & over again!

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

PROGRAMMING FUNDAMENTALS

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park

CSC 1351: Quiz 6: Sort and Search

CS 3410 Ch 7 Recursion

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

Pace University. Fundamental Concepts of CS121 1

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion

NCS 301 DATA STRUCTURE USING C

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

Introduction to Software Development (ISD) Week 3

Computer Science is...

ECE 122. Engineering Problem Solving with Java

RECURSION. Many Slides from Ken Birman, Cornell University

McGill University Faculty of Science School of Computer Science. MIDTERM EXAMINATION - Sample solutions. COMP-250: Introduction to Computer Science

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

CS171:Introduction to Computer Science II

Chapter 1: Introduction to Computers, Programs, and Java

Recursion Chapter 3.5

Loops and Expression Types

STUDENT LESSON A9 Recursion

Object Oriented Programming Exception Handling

CSE 2123 Recursion. Jeremy Morris

1. Answer as shown or -2 unless question allows partial credit. No points off for differences in spacing, capitalization, commas, and braces

Recursion. Chapter 11

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Top-Down Program Development

Project Compiler. CS031 TA Help Session November 28, 2011

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

Transcription:

COMP-202 Recursion

Recursion Recursive Definitions Run-time Stacks Recursive Programming Recursion vs. Iteration Indirect Recursion Lecture Outline 2

Recursive Definitions (1) A recursive definition is one which uses the word or concept being defined in the definition itself Consider the following list of numbers: 24, 88, 40, 37 Such a list can be defined as A LIST is either a number or a number comma LIST That is, a LIST is defined to be a single number, or a number followed by a comma followed by a LIST The concept of a LIST is used to define itself 3

Recursive Definitions (2) The recursive part of the LIST definition is used several times, terminating with the non-recursive part: number comma LIST 24, 88, 40, 37 number comma LIST 88, 40, 37 number comma LIST 40, 37 number 37 4

Infinite Recursions All recursive definitions have to have a nonrecursive part If they didn't, there would be no way to terminate the recursive path Such a definition would cause infinite recursion This problem is similar to an infinite loop The non-recursive part is often called the base case 5

Recursive Definition Example (1) n!, for any positive integer n, is defined to be the product of all integers between 1 and n inclusive This definition can be expressed recursively as: 1! = 1 n! = n * (n-1)! The concept of the factorial is defined in terms of another factorial Eventually, the base case of 1! is reached 6

Recursive Definition Example (2) 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 120 120 24 6 2 1 7

Recursive Programming A method in Java can invoke itself; if set up that way, it is called a recursive method The code of a recursive method must be structured to handle both the base case and the recursive case Each call to the method sets up a new execution environment, with new parameters and local variables As always, when the method completes, control returns to the method that invoked it (which may be an earlier invocation of itself) 8

An Executing Program in Memory Dynamic Data Run-time Heap: where objects are created Run-time Stack: memory needed for method calls, e.g. parameters, local variables, return values Program Code Static Data Your compiled code All non-local data: class definitions, static variables, constants 9

Method Call Frame At every call to a method a frame is added to the top of the stack. This is referred to as a push. Method Call Frame When the method terminates the frame is removed from the top of the stack. This is referred to as a pop. Stacks function much like a stack of plates. You put plates on the top and you remove them from the top. Return Address Return Value Parameters Local Variables 10

Recursive Programming Example (1) Consider the problem: Compute the sum of all the numbers between 1 and any positive integer n sum(5) = 5 + 4 + 3 + 2 + 1 11

Recursive Programming Example (2) public class RecursionTest { public int sum(int n) { int result = 0; if (n == 1) // base case! result = 1; else! // recursive part! result = n + sum(n-1); return result; public static void main(string [] args) { System.out.println(sum(3)); 12

Recursive Programming Example (3) public int sum(int n) { int result = 0; if (n == 1) // base case result = 1; else! // recursive part result = n + sum(n-1); return result; main: println(sum(3)) Method Call Frame result = 3 + sum(2) ra main rv 6 n 3 result 06 result = 2 + sum(1) ra sum(3) rv 3 n 2 result 03 result = 1 ra sum(2) rv 1 n 1 result 01 13

Recursive vs. Iterative public int sum_recursive(int n) { int result = 0; if (n == 1) // base case result = 1; else! // recursive part result = n + sum_recursive(n-1); return result; public int sum_iterative(int n) { int result = 0; for (int i = 1; i <= n; i++) result += i; return result; 14

Recursion: When to Use It (1) Note that just because we can use recursion to solve a problem, doesn't mean we should (there is a lot of overhead: method calls, variable declarations, etc.) For instance, we usually would not use recursion to solve the sum of 1 to N problem, because the iterative version is easier to understand, and also faster However, for some problems, recursion provides an elegant solution, often cleaner than an iterative version You must carefully decide whether recursion is the correct technique for any problem 15

Palindrome Testing public class PalindromeTesters { public static boolean iterativetester (String str { int left = 0; int right = str.length() - 1; while (left < right && str.charat(left) == str.charat(right)){ left++; right--; return (left >= right); public static boolean recursivetester (String str)! { boolean result = false; if (str.length() <= 1) result = true; else result = (str.charat(0) == str.charat(str.length() - 1)) && recursivetester(str.substring(1,str.length()-1)); return result; 16

Recursion: When to Use It (2) Notice that we have many ways to repeatedly perform some statements: do while while for Recursion They all do the same thing, so the choice should be based on some benefit: Easier to program Resource usage: runs faster, uses less memory Ideally you want to optimize on both criteria 17

Designing for Recursion A recursive algorithm always looks like this: Base Case The part of the loop that has the stop condition. It also returns the default (simplest case) result Incrementing Part The part of the program that moves us on to the next data value. Incrementing variable Reading data Moving to a new data item in a structure (like array) Recursion Part The part of the program that initiates the recursion, i.e. makes the recursive call Note that the Incrementing and Recursion Parts are often together in the same statement (but not always) 18

Indirect Recursion A method invoking itself is considered to be direct recursion A method could invoke another method, which invokes another, etc., until eventually the original method is invoked again For example, method m1 could invoke m2, which invokes m3, which in turn invokes m1 again This is called indirect recursion, and requires all the same care as direct recursion It is often more difficult to trace and debug 19