CSE 230 Intermediate Programming in C and C++ Recursion

Similar documents
CSE 214 Computer Science II Recursion

CSE 230 Computer Science II (Data Structure) Introduction

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

1.7 Recursion. Department of CSE

CSE 230 Intermediate Programming in C and C++ Functions

CSE 230 Intermediate Programming in C and C++ Binary Tree

CSE 230 Intermediate Programming in C and C++ Arrays and Pointers

CSE 214 Computer Science II Introduction to Tree

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

CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings

Fundamentals of Programming Session 13

EK131 E5 Introduction to Engineering

Programming with Recursion. What Is Recursion?

Koch snowflake. Fractal Fern

CSE 214 Computer Science II Heaps and Priority Queues

CS 310 Advanced Data Structures and Algorithms

CSE 130 Introduction to Programming in C Control Flow Revisited

PDF created with pdffactory Pro trial version Recursion

CSE 214 Computer Science II Java Classes and Information Hiding

CSE 214 Computer Science II Searching

NCS 301 DATA STRUCTURE USING C

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

CS103L SPRING 2017 UNIT 8: RECURSION

Objectives. Recursion. One Possible Way. How do you look up a name in the phone book? Recursive Methods Must Eventually Terminate.

CSE 230 Intermediate Programming in C and C++

CSE 214 Computer Science II Final Review II

Programming II (CS300)

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub

What is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis:

ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion

CSE 230 Intermediate Programming in C and C++

CSE 230 Intermediate Programming in C and C++

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

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

Lecture 16: Introduction to Dynamic Programming Steven Skiena. Department of Computer Science State University of New York Stony Brook, NY

Chapter 10: Recursive Problem Solving

COMP-202 Unit 8: Recursion. CONTENTS: Recursion in Java More complex examples

CS 161 Intro to CS I. Finish Pointers/Start Recursion

Programming II (CS300)

Software Development. Modular Design and Algorithm Analysis

Halting Measures and Termination Arguments

ALGORITHM DESIGN DYNAMIC PROGRAMMING. University of Waterloo

Recursive Problem Solving

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself.

Programming II (CS300)

Loops. CSE 114, Computer Science 1 Stony Brook University

CSCS-200 Data Structure and Algorithms. Lecture

EC 413 Computer Organization

EE 368. Weeks 4 (Notes)

COP 4020 Fall 2005 Presentation Joshua Burkholder 2005 NOV 27. Recursion. What, Why, How, When, and What If?

CS 231 Data Structures and Algorithms Fall Recursion and Binary Trees Lecture 21 October 24, Prof. Zadia Codabux

ECE 2574: Data Structures and Algorithms - Recursion Part I. C. L. Wyatt

You should know the first sum above. The rest will be given if you ever need them. However, you should remember that,, and.

RECURSION: n. SEE RECURSION 3

CSE 214 Computer Science II Stack

CS 380 ALGORITHM DESIGN AND ANALYSIS

RECURSION. Data Structures & SWU Rachel Cardell- Oliver

Recursion. notes Chapter 8

UNIT 5A Recursion: Basics. Recursion

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself?

CS 206 Introduction to Computer Science II

Function with default arguments

Reduction & Recursion Overview

RECURSION, RECURSION, (TREE) RECURSION! 3

Solving problems by recursion

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Decision-Making and Repetition

Instructors: Daniel Deutch, Amir Rubinstein, Teaching Assistants: Amir Gilad, Michal Kleinbort

Standard Version of Starting Out with C++, 4th Edition. Chapter 19 Recursion. Copyright 2003 Scott/Jones Publishing

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

RECURSION, RECURSION, (TREE) RECURSION! 2

Function Calls. 1 Administrivia. Tom Kelliher, CS 240. Feb. 13, Announcements. Collect homework. Assignment. Read

Lecture 12: Dynamic Programming Part 1 10:00 AM, Feb 21, 2018

Chapter 17 Recursion

CS 206 Introduction to Computer Science II

RECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012

3. You are writing code for a business application by using C#. You write the following statement to declare an array:

What is an Algorithm?

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself? contains a reference to itself.

ITERATION AND RECURSION 3

Recursive Functions. Biostatistics 615 Lecture 5

Function Calls. Tom Kelliher, CS 220. Oct. 24, SPIM programs due Wednesday. Refer to homework handout for what to turn in, and how.

C22a: Problem Solving using Recursion

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

A Useful Case. A Fruitful Application of Recursion: n-queen problem

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

Lecture 10: Recursive Functions. Computer System and programming in C 1

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

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

Computer Programming

What is recursion? Recursion. Recursive message() modified. How can a function call itself? contains a reference to itself. Week 10. Gaddis:

Recursion. Chapter 11. Chapter 11 1

142

C Functions. Object created and destroyed within its block auto: default for local variables

CS1 Recitation. Week 2

Dynamic Programming. An Introduction to DP

CSE 341 Lecture 5. efficiency issues; tail recursion; print Ullman ; 4.1. slides created by Marty Stepp

RECURSION 3. 1 Recursion COMPUTER SCIENCE 61A. June 30, 2016

Transcription:

CSE 230 Intermediate Programming in C and C++ Recursion Fall 2017 Stony Brook University Instructor: Shebuti Rayana

What is recursion? Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem first Recursion is a technique that solves a problem by solving a smaller problem of the same type Shebuti Rayana (CS, Stony Brook University) 2

Recursive Function A function is called recursive if it calls itself In C, all functions can be used recursively Example: This will act like an infinite loop Shebuti Rayana (CS, Stony Brook University) 3

Recursive Function: Example This code computes the sum of first n positive integers. For n = 4 Function Call Value returned sum(1) 1 sum(2) 2+sum(1) or 2+1 sum(3) 3+sum(2) or 3+2+1 Sum(4) 4+sum(3) or 4+3+2+1 Shebuti Rayana (CS, Stony Brook University) 4

Recursive Function There is a base case (or cases) that is tested upon entry And a general recursive case in which one of the variables, is passed as an argument in such a way as to ultimately lead to the base case. Shebuti Rayana (CS, Stony Brook University) 5

Problems Defined Recursively There are many problems whose solution can be defined recursively Example: factorial n n!= 1 if n = 0 (n-1)!*n if n > 0 (recursive solution) n!= 1 if n = 0 1*2*3* *(n-1)*n if n > 0 (closed form solution) Shebuti Rayana (CS, Stony Brook University) 6

Coding the Factorial Function Recursive Implementation int Factorial(int n) { if (n==0) // base case return 1; else return n * Factorial(n-1); } For n > 12 this function will return incorrect value as the final result is too big to fit in an integer Shebuti Rayana (CS, Stony Brook University) 7

Shebuti Rayana (CS, Stony Brook University) 8

Coding the Factorial Function (cont.) Iterative Implementation int Factorial(int n) { int fact = 1; for(int count = 2; count <= n; count++) fact = fact * count; return fact; } Both recursive and iterative version returns same value Shebuti Rayana (CS, Stony Brook University) 9

Another Example: n choose k (combinations) Given n things, how many different sets of size k can be chosen? n n-1 n-1 = +, 1 < k < n (recursive solution) k k k-1 n n! =, 1 < k < n (closed-form solution) k k!(n-k)! with base cases: n n = n (k = 1), = 1 (k = n) 1 n Shebuti Rayana (CS, Stony Brook University) 10

n choose k implementation int Combinations(int n, int k) { } if(k == 1) // base case 1 return n; else if (n == k) // base case 2 else return 1; return(combinations(n-1, k) + Combinations(n-1, k-1)); Shebuti Rayana (CS, Stony Brook University) 11

Shebuti Rayana (CS, Stony Brook University) 12

Recursion vs Iteration Iteration can be used in place of recursion An iterative algorithm uses a looping construct A recursive algorithm uses a branching structure Recursive solutions are often less efficient, in terms of both time and space, than iterative solutions Recursion can simplify the solution of a problem, often resulting in shorter, more easily understood source code Shebuti Rayana (CS, Stony Brook University) 13

How to write a recursive function? Determine the size factor Determine the base case(s) (the one for which you know the answer) Determine the general case(s) (the one where the problem is expressed as a smaller version of itself) Verify the algorithm (use the "Three-Question-Method") Shebuti Rayana (CS, Stony Brook University) 14

Three Question Verification 1. The Base-Case Question Is there a non-recursive way out of the function, and does the routine work correctly for this "base" case? 2. The Smaller-Caller Question Does each recursive call to the function involve a smaller case of the original problem, leading inescapably to the base case? 3. The General-Case Question Assuming that the recursive call(s) work correctly, does the whole function work correctly? Shebuti Rayana (CS, Stony Brook University) 15

Recursion: Calculation of Fibonacci Sequence Recursive solution f " = 0, f % = 1, f '(% = f ' + f '*%, for i = 1, 2, Except for f " and f %, every element in the sequence is the sum of the previous two elements The sequence begins 0, 1, 1, 2, 3, 5, 8, int Fibonacci(int n) { if(n <= 1) // base case return n; else return(fibonacci(n-1) + Fibonacci(n-2)); } Shebuti Rayana (CS, Stony Brook University) 16

Recursion: Calculation of Fibonacci Sequence Shebuti Rayana (CS, Stony Brook University) 17

Number of Function Calls for Recursive Fibonacci Value of n Value of Fibonacci(n) 0 1 2 23 24 42 43 0 1 1 28657 46368 267914296 433494437 #of function calls 1 1 3 92735 150049 866988873 1402817465 A large number of function call is required to compute the nth fibonacci for even moderate values of n Shebuti Rayana (CS, Stony Brook University) 18

Pitfalls of Recursion Missing base case failure to provide an escape case. No guarantee of convergence failure to include within a recursive function a recursive call to solve a subproblem that is not smaller. Excessive space requirements - a function calls itself recursively an excessive number of times before returning; the space required for the task may be prohibitive. Excessive recomputation illustrated in the recursive Fibonacci method which ignores that several sub- Fibonacci values have already been computed. Shebuti Rayana (CS, Stony Brook University) 19