Building Java Programs

Similar documents
CSE 143 Lecture 11. Decimal Numbers

CSE 143 Lecture 10. Recursive Programming. reading: slides adapted from Marty Stepp and Hélène Martin

CSE 143 Lecture 13. Recursive Programming. reading: slides created by Marty Stepp

Recursion. Readings: RS Chapter 12. Recursion. Recursion: The definition of an operation in terms of itself.

Lecture 19: Recursion

Announcements. Recursion and why study it. Recursive programming. Recursion basic idea

CSE 143. Computer Programming II

Lecture 11: Recursion (hard)

C22a: Problem Solving using Recursion

OVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion?

CS 106X, Lecture 7 Introduction to Recursion

q To develop recursive methods for recursive mathematical functions ( ).

q To develop recursive methods for recursive mathematical functions ( ).

CS212 Midterm. 1. Read the following code fragments and answer the questions.

CIS265 - Spring Exam 2 First Name Last Name CSU#

CSE 2123 Recursion. Jeremy Morris

CS/CE 2336 Computer Science II

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Lecture 6 CS2110 Spring 2013 RECURSION

Recursive definition: A definition that is defined in terms of itself. Recursive method: a method that calls itself (directly or indirectly).

CS 3410 Ch 7 Recursion

Recursion. Tracing Method Calls via a Stack. Beyond this lecture...

Review for Test 1 (Chapter 1-5)

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

Recursion. Recursion is: Recursion splits a problem:

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Building Java Programs

Jalil Boudjadar, Tommy Färnqvist. IDA, Linköping University

RECURSION. Many Slides from Ken Birman, Cornell University

Programming II (CS300)

CSE 143 SAMPLE MIDTERM

If you are going to form a group for A2, please do it before tomorrow (Friday) noon GRAMMARS & PARSING. Lecture 8 CS2110 Spring 2014

Fun facts about recursion

Programming II (CS300)

public static void main(string args[]){ arraylist(); recursion();

Programming II (CS300)

Csci 102: Sample Exam

Recursion and Recursive Structures

CSC 1052 Algorithms & Data Structures II: Recursion

GRAMMARS & PARSING. Lecture 7 CS2110 Fall 2013

Binary Search. Roland Backhouse February 5th, 2001

Question: Total Points: Score:

Unit 10: exception handling and file I/O

Reduction & Recursion Overview

Lecture 7 CS2110 Fall 2014 RECURSION

CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam

9/16/14. Overview references to sections in text RECURSION. What does generic mean? A little about generics used in A3

CS 180 Final Exam Review 12/(11, 12)/08

CMSC 150 LECTURE 7 RECURSION

Notes from the Boards Set BN19 Page

Pace University. Fundamental Concepts of CS121 1

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

DM503 Programming B. Peter Schneider-Kamp.

CSE 143 Lecture 10. Recursion

JAVA - FILE CLASS. The File object represents the actual file/directory on the disk. Below given is the list of constructors to create a File object

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

Testing and Debugging

Topic 7: Algebraic Data Types

Recommendation: Play the game and attempt to answer the questions yourself without looking at the answers. You ll learn much less if you just look at

1B1b Classes in Java Part I

CSE 373 Section Handout #1 Numeric Data

A function that invokes itself is said to

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Lecture 6: Recursion RECURSION

Text Input and Conditionals

CSE 143. Lecture 9: introduction to recursion reading: 12.1

Language Reference Manual

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

CS 307 Midterm 2 Fall 2010

Control Structures in Java if-else and switch

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Recursion. Recursion [Bono] 1

COMP102: Test. 31 August, 2005

Unit 10: Sorting/Searching/Recursion

Exam Datastrukturer. DIT960 / DIT961, VT-18 Göteborgs Universitet, CSE

CMPSCI 250: Introduction to Computation. Lecture #1: Things, Sets and Strings David Mix Barrington 22 January 2014

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

CS 206 Introduction to Computer Science II

0. What is the capital of Canada? (4pts) a. Toronto b. Quebec c. Ottawa d. Vancouver e. Calgary f. Not sure

Introduction to Programming (Java) 4/12

CSE 143 SAMPLE MIDTERM SOLUTION

DM550 Introduction to Programming part 2. Jan Baumbach.

t 1 =2 t n =3t n 1 1,n 1

Account joeacct = new Account (100, new Account (500)); Account joeacct = new Account (100, new Account (500, null));

Repetitive Program Execution

CSE 143 Lecture 19. Binary Trees. read slides created by Marty Stepp

1KOd17RMoURxjn2 CSE 20 DISCRETE MATH Fall

Sample Questions for Midterm Exam 2

AP Computer Science A

c) And last but not least, there are javadoc comments. See Weiss.

Module 10. Recursion. Adapted from Absolute Java, Rose Williams, Binghamton University

Discussion 2C Notes (Week 5, February 4) TA: Brian Choi Section Webpage:

AP CS Fall Semester Final

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

AP Programming - Chapter 17 Lecture page 1 of 5

Analyzing Complexity of Lists

CMP 326 Midterm Fall 2015

CS1004: Intro to CS in Java, Spring 2005

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

Transcription:

Building Java Programs Chapter 12 recursive programming reading: 12.2-12.4

2

Recursion and cases Every recursive algorithm involves at least 2 cases: base case: simple problem that can be solved directly. recursive case: more complex occurrence of the problem that cannot be directly answered, but can instead be described in terms of smaller occurrences of the same problem. Some recursive algorithms have more than one base or recursive case, but all have at least one of each. A crucial part of recursive programming is identifying these cases. 3

Exercise Write a recursive method pow accepts an integer base and exponent and returns the base raised to that exponent. Example: pow(3, 4) returns 81 Solve the problem recursively and without using loops. 4

An optimization Notice the following mathematical property: 3 12 = 531441 = 9 6 = (3 2 ) 6 531441 = (9 2 ) 3 = ((3 2 ) 2 ) 3 When does this "trick" work? How can we incorporate this optimization into our pow method? What is the benefit of this trick if the method already works? 5

Exercise Write a recursive method printbinary that accepts an integer and prints that number's representation in binary (base 2). Example: printbinary(7) prints 111 Example: printbinary(12) prints 1100 Example: printbinary(42) prints 101010 place 10 1 32 16 8 4 2 1 value 4 2 1 0 1 0 1 0 Write the method recursively and without using any loops. 6

Repeat Digits How did we break the number apart? public static int repeatdigits(int n) { if (n < 10) { return (10 * n) + n; else { int a = repeatdigits(n / 10); int b = repeatdigits(n % 10); return (100 * a) + b; 7

Case analysis Recursion is about solving a small piece of a large problem. What is 69743 in binary? Do we know anything about its representation in binary? Case analysis: What is/are easy numbers to print in binary? Can we express a larger number in terms of a smaller number(s)? 8

printbinary solution // Prints the given integer's binary representation. // Precondition: n >= 0 public static void printbinary(int n) { if (n < 2) { // base case; same as base 10 System.out.println(n); else { // recursive case; break number apart printbinary(n / 2); printbinary(n % 2); Can we eliminate the precondition and deal with negatives? 9

Exercise Write a recursive method ispalindrome accepts a String and returns true if it reads the same forwards as backwards. ispalindrome("madam") ispalindrome("racecar") ispalindrome("step on no pets") ispalindrome("able was I ere I saw elba") ispalindrome("java") ispalindrome("rotater") ispalindrome("byebye") ispalindrome("notion") true true true true false false false false 10

Exercise solution // Returns true if the given string reads the same // forwards as backwards. // Trivially true for empty or 1-letter strings. public static boolean ispalindrome(string s) { if (s.length() < 2) { return true; // base case else { char first = s.charat(0); char last = s.charat(s.length() - 1); if (first!= last) { return false; // recursive case String middle = s.substring(1, s.length() - 1); return ispalindrome(middle); 11

Exercise solution 2 // Returns true if the given string reads the same // forwards as backwards. // Trivially true for empty or 1-letter strings. public static boolean ispalindrome(string s) { if (s.length() < 2) { return true; // base case else { return s.charat(0) == s.charat(s.length() - 1) && ispalindrome(s.substring(1, s.length() - 1)); 12

13

Exercise Write a method crawl accepts a File parameter and prints information about that file. If the File object represents a normal file, just print its name. If the File object represents a directory, print its name and information about every file/directory inside it, indented. cse143 handouts syllabus.doc lecture_schedule.xls homework 1-tiles TileMain.java TileManager.java index.html style.css recursive data: A directory can contain other directories. 14

Recursive Data A file is one of A simple file A directory containing files Directories can be nested to an arbitrary depth 15

File objects A File object (from the java.io package) represents a file or directory on the disk. Constructor/method File(String) canread() delete() exists() getname() isdirectory() length() listfiles() renameto(file) Description creates File object representing file with given name returns whether file is able to be read removes file from disk whether this file exists on disk returns file's name returns whether this object represents a directory returns number of bytes in file returns a File[] representing files in this directory changes name of file 16

Public/private pairs We cannot vary the indentation without an extra parameter: public static void crawl(file f, String indent) { Often the parameters we need for our recursion do not match those the client will want to pass. In these cases, we instead write a pair of methods: 1) a public, non-recursive one with parameters the client wants 2) a private, recursive one with the parameters we really need 17

Exercise solution 2 // Prints information about this file, // and (if it is a directory) any files inside it. public static void crawl(file f) { crawl(f, ""); // call private recursive helper // Recursive helper to implement crawl/indent behavior. private static void crawl(file f, String indent) { System.out.println(indent + f.getname()); if (f.isdirectory()) { // recursive case; print contained files/dirs File[] subfiles = f.listfiles(); for (int i = 0; i < subfiles.length; i++) { crawl(subfiles[i], indent + " "); 18

Recursion Challenges Forgetting a base case Infinite recursion resulting in StackOverflowError Working away from the base case The recursive case must make progress towards the base case Infinite recursion resulting in StackOverflowError Running out of memory Even when making progress to the base case, some inputs may require too many recursive calls: StackOverflowError Recomputing the same subproblem over and over again Refining the algorithm could save significant time 19