CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

Similar documents
Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

What Is Recursion? Recursion. Binary search example postponed to end of lecture

recursion here it is in C++ power function cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Chapter 5. Recursion. Data Structures and Algorithms in Java

CS 2412 Data Structures. Chapter 2 Stacks and recursion

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Solving Problems Recursively

csci 210: Data Structures Recursion

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

Chapter 5 Functions. Introducing Functions

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Sample Questions Csci 1112 A. Bellaachia

St S a t ck a ck nd Qu Q eue 1

Conditions & Boolean Expressions

Recursive Fibonacci and the Stack Frame. the Fibonacci function. The Fibonacci function defines the Fibonacci sequence, using a recursive definition :

CSI33 Data Structures

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Computer Systems Architecture

Data Structures. Algorithm Performance and Big O Analysis

While Loop. 6. Iteration

10CS35: Data Structures Using C

! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1

Comp151. Definitions & Declarations

Pseudo code Tutorial and Exercises Teacher s Version

Analysis of Binary Search algorithm and Selection Sort algorithm

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

The While Loop. Objectives. Textbook. WHILE Loops

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Chapter 5. Selection 5-1

Recursion and Recursive Backtracking

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Data Structures, Practice Homework 3, with Solutions (not to be handed in)

Cpt S 223. School of EECS, WSU

C++FA 5.1 PRACTICE MID-TERM EXAM

PIC 10A. Lecture 7: Graphics II and intro to the if statement

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Common Data Structures

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Module 2 Stacks and Queues: Abstract Data Types

6. Control Structures

Stack Allocation. Run-Time Data Structures. Static Structures

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

More MIPS: Recursion. Computer Science 104 Lecture 9

Moving from CS 61A Scheme to CS 61B Java

Outline. The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack. Stacks 2

The if Statement and Practice Problems

Recursion and Dynamic Programming. Biostatistics 615/815 Lecture 5

Section IV.1: Recursive Algorithms and Recursion Trees

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Algorithm Design and Recursion

C++FA 3.1 OPTIMIZING C++

CSCI 528: OBJECT ORIENTED PROGRAMMING, Fall 2015

Recursion vs. Iteration Eliminating Recursion

Introduction to Stacks

Answers to Review Questions Chapter 7

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

>

13 Classes & Objects with Constructors/Destructors

Functional Programming in C++11

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

C++ Input/Output: Streams

PES Institute of Technology-BSC QUESTION BANK

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Passing 1D arrays to functions.

12-6 Write a recursive definition of a valid Java identifier (see chapter 2).

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Programming Exercises

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Subtopics - Functions Function Declaration Function Arguments Return Statements and values. By Hardeep Singh

CmpSci 187: Programming with Data Structures Spring 2015

Bevezetés a C++ Standard Template Library-be

Compiler Construction

Data Structures/Stacks and Queues

Introduction to Programming (in C++) Multi-dimensional vectors. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Chapter 8 Selection 8-1

from Recursion to Iteration

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Lecture Notes on Linear Search

Algorithms. Margaret M. Fleck. 18 October 2010

Transcription:

Brad Rippe CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++ Recursion

Recursion CHAPTER 14

Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively

What is recursion? When a function is defined in terms of itself A recursive function is a function that calls itself void foo(int n) { } return foo(n-1);

Objectives To know what is a recursive function and the benefits of using recursive To determine the base cases in a recursive function To understand how recursive function calls are handled in a call stack To solve problems using recursion To use an overloaded helper function to derive a recursive function To understand the relationship and difference between recursion and iteration

Factorial Function factorial(0) = 1; factorial(n) = n*factorial(n-1); /////////////////////////////////// Definition ///////////////////////////////// int factorial(int n) { if (n == 0) { // Base Case return 1; } else { return n * factorial(n - 1); // Recursive call } } Factorial.cpp

Computing Factorial factorial(3) factorial(0) = 1; factorial(n) = n*factorial(n-1);

Computing Factorial factorial(3) = 3 * factorial(2) factorial(0) = 1; factorial(n) = n*factorial(n-1);

Computing Factorial factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) factorial(0) = 1; factorial(n) = n*factorial(n-1);

Computing Factorial factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * ( 2 * (1 * factorial(0))) factorial(0) = 1; factorial(n) = n*factorial(n-1);

Computing Factorial factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * ( 2 * (1 * factorial(0))) = 3 * ( 2 * ( 1 * 1))) factorial(0) = 1; factorial(n) = n*factorial(n-1);

Computing Factorial factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * ( 2 * (1 * factorial(0))) = 3 * ( 2 * ( 1 * 1))) = 3 * ( 2 * 1) factorial(0) = 1; factorial(n) = n*factorial(n-1);

Computing Factorial factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * ( 2 * (1 * factorial(0))) = 3 * ( 2 * ( 1 * 1))) = 3 * ( 2 * 1) = 3 * 2 factorial(0) = 1; factorial(n) = n*factorial(n-1);

Computing Factorial factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * ( 2 * (1 * factorial(0))) = 3 * ( 2 * ( 1 * 1))) = 3 * ( 2 * 1) = 3 * 2 = 6 factorial(0) = 1; factorial(n) = n*factorial(n-1);

animation Trace Recursive factorial Executes factorial(4) factorial(4) Step 9: return 24 Step 8: return 6 Step 0: executes factorial(4) return 4 * factorial(3) Step 1: executes factorial(3) return 3 * factorial(2) Stack Step 7: return 2 return 2 * factorial(1) Step 2: executes factorial(2) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 return 1 Main method

animation Trace Recursive factorial Step 9: return 24 Step 8: return 6 Step 7: return 2 factorial(4) return 4 * factorial(3) Step 6: return 1 Step 0: executes factorial(4) Step 1: executes factorial(3) return 3 * factorial(2) return 2 * factorial(1) Step 5: return 1 Step 2: executes factorial(2) return 1 * factorial(0) Step 3: executes factorial(1) return 1 Step 4: executes factorial(0) Executes factorial(3) Function Stack Stack Frame Stack for factorial(4) Main method Note the change in the function stack. Each call to factorial pushes the function onto the stack.

animation Trace Recursive factorial factorial(4) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Executes factorial(2) Stack Step 7: return 2 return 2 * factorial(1) Step 2: executes factorial(2) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 return 1 for factorial(3) for factorial(4) Main method

animation Trace Recursive factorial factorial(4) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) Executes factorial(1) Stack Step 2: executes factorial(2) Step 7: return 2 return 2 * factorial(1) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 return 1 for factorial(2) for factorial(3) for factorial(4) Main method

animation Trace Recursive factorial factorial(4) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 Executes factorial(0) Stack return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 return 2 * factorial(1) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 return 1 for factorial(1) for factorial(2) for factorial(3) for factorial(4) Main method

animation Trace Recursive factorial Step 9: return 24 Step 8: return 6 Step 7: return 2 factorial(4) return 4 * factorial(3) Step 6: return 1 Step 0: executes factorial(4) Step 1: executes factorial(3) return 3 * factorial(2) return 2 * factorial(1) Step 5: return 1 Step 2: executes factorial(2) return 1 * factorial(0) Step 3: executes factorial(1) return 1 Step 4: executes factorial(0) returns 1 Stack for factorial(0) for factorial(1) for factorial(2) for factorial(3) for factorial(4) Main method

animation Trace Recursive factorial factorial(4) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 returns factorial(0) Stack return 3 * factorial(2) Step 2: executes factorial(2) Step 7: return 2 return 2 * factorial(1) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 return 1 for factorial(1) for factorial(2) for factorial(3) for factorial(4) Main method

animation Trace Recursive factorial factorial(4) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) returns factorial(1) Stack Step 2: executes factorial(2) Step 7: return 2 return 2 * factorial(1) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 return 1 for factorial(2) for factorial(3) for factorial(4) Main method

animation Trace Recursive factorial factorial(4) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) returns factorial(2) Stack Step 7: return 2 return 2 * factorial(1) Step 2: executes factorial(2) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 return 1 for factorial(3) for factorial(4) Main method

animation Trace Recursive factorial factorial(4) Step 0: executes factorial(4) Step 9: return 24 return 4 * factorial(3) Step 1: executes factorial(3) Step 8: return 6 return 3 * factorial(2) returns factorial(3) Stack Step 7: return 2 return 2 * factorial(1) Step 2: executes factorial(2) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 return 1 for factorial(4) Main method

animation Trace Recursive factorial returns factorial(4) factorial(4) Step 9: return 24 Step 8: return 6 Step 0: executes factorial(4) return 4 * factorial(3) Step 1: executes factorial(3) return 3 * factorial(2) Stack Step 7: return 2 return 2 * factorial(1) Step 2: executes factorial(2) Step 3: executes factorial(1) Step 6: return 1 return 1 * factorial(0) Step 4: executes factorial(0) Step 5: return 1 return 1 Main method

factorial(4) Stack Trace 5 for factorial(0) 4 for factorial(1) for factorial(1) 3 for factorial(2) for factorial(2) for factorial(2) 2 for factorial(3) for factorial(3) for factorial(3) for factorial(3) 1 for factorial(4) for factorial(4) for factorial(4) for factorial(4) for factorial(4) 6 for factorial(1) for factorial(2) 7 for factorial(2) for factorial(3) for factorial(3) 8 for factorial(3) for factorial(4) for factorial(4) for factorial(4) 9 for factorial(4)

Fibonacci Numbers Finonacci series: 0 1 1 2 3 5 8 13 21 34 55 89 indices: 0 1 2 3 4 5 6 7 8 9 10 11 fib(0) = 0; fib(1) = 1; fib(index) = fib(index -1) + fib(index -2); assume index >=2 fib(3) = fib(2) + fib(1) = (fib(1) + fib(0)) + fib(1) = (1 + 0) +fib(1) = 1 + fib(1) = 1 + 1 = 2 Fibonacci.cpp

Fibonnaci Numbers, cont.

Characteristics of Recursion All recursive methods have the following characteristics: One or more base cases (the simplest case) are used to stop recursion. We know how to solve this case. Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. In general, to solve a problem using recursion, you break it into subproblems. If a subproblem resembles the original problem, you can apply the same approach to solve the subproblem recursively. This subproblem is almost the same as the original problem in nature with a smaller size.

Problem Solving Using Recursion Let us consider a simple problem of printing a message for n times. You can break the problem into two subproblems: 1. print the message one time 2. print the message for n-1 times. The second problem is the same as the original problem with a smaller size. The base case for the problem is n==0.

Print Message Recursively void printmsg(char *amessage, int atimes) { if(atimes >= 1) { cout << amessage << atimes << endl; printmsg(amessage, atimes-1); } }

Think Recursively Many of the problems presented in the early chapters can be solved using recursion if you think recursively. For example, the palindrome problem can be solved recursively as follows: bool ispalindrome(const char* const astring) { if(strlen(astring) <= 1) { return true; } else if(astring[0]!= astring[strlen(astring)-1]) { return false; } else { return ispalindrome(substring(astring, 1, strlen(astring)-2)); } }

Recursive Selection Sort 1. Find the largest number in the list and swaps it with the last number. 2. Ignore the last number and sort the remaining ints in the list recursively. recursiveselectionsort.cpp

Towers of Hanoi There are n disks labeled 1, 2, 3,..., n, and three towers labeled A, B, and C. No disk can be on top of a smaller disk at any time. All the disks are initially placed on tower A. Only one disk can be moved at a time, and it must be the top disk on the tower.

Towers of Hanoi, cont. A B C A B C Original position Step 4: Move disk 3 from A to B A B C A B C Step 1: Move disk 1 from A to B Step 5: Move disk 1 from C to A A B C A B C Step 2: Move disk 2 from A to C Ste p 6: Move disk 2 from C to B A B C A B C Step 3: Move disk 1 from B to C Step 7: Mve disk 1 from A to B

Solution to Towers of Hanoi The Towers of Hanoi problem can be decomposed into three subproblems. n-1 disks n-1 disks...... A B C A B C Original position Step2: Move disk n from A to C n-1 disks n-1 disks...... A B C A B C Step 1: Move the first n -1 disks from A to C recursively Step3: Move n -1 disks from C to B recursively

Solution to Towers of Hanoi Move the first n - 1 disks from A to C with the assistance of tower B. Move disk n from A to B. Move n - 1 disks from C to B with the assistance of tower A.