Recursion Using Stacks. What’s Going On? int main() { // Get Input int x, y; cout << "Enter value x: "; cin >> x; // Call f y = f(x); // Print results.

Slides:



Advertisements
Similar presentations
Pass by Value. COMP104 Pass by Value / Slide 2 Passing Parameters by Value * A function returns a single result (assuming the function is not a void function)
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline some useful problems.
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
If Statements & Relational Operators Programming.
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
Computer Science 1620 Loops.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
More on Functions Programming. COMP104 Lecture 19 / Slide 2 Passing Parameters by Reference l To have a function with multiple outputs, we have to use.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
Programming Switch command. COMP102 Prog. Fundamentals: Switch command / Slide 2 Multiple Selection: The switch Statement value1 action 1 value2 action.
1 9/28/07CS150 Introduction to Computer Science 1 Loops section 5.2, 5.4, 5.7.
1 10/11/06CS150 Introduction to Computer Science 1 do/while and Nested Loops.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Chapter 4 Summation.
Functions:Passing Parameters by Value Programming.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
Ordered Arrays An array is ordered if the elements are in ascending or descending order. The array may be ordered numerically or alphabetically (which.
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
Inline Function. 2 Expanded in a line when it is invoked Ie compiler replace the function call with function code To make a function inline the function.
PRINCIPLES OF PROGRAMMING Revision. A Computer  A useful tool for solving a great variety of problems.  To make a computer do anything (i.e. solve.
FALL 2001ICOM Lecture 21 ICOM 4015 Advanced Programming Lecture 2 Procedural Abstraction Reading: LNN Chapter 4, 14 Prof. Bienvenido Velez.
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Stacks. An alternative storage structure for collections of entities is a stack. A stack is a simplified form of a linked list in which all insertions.
Recursion. Definition Recursion is a function calling on itself over and over until reaching an end state. One such example is factorial. 10! = 10 * 9.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
CS1201: Programming Language 2 Recursion By: Nouf Almunyif.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas.
COMPUTER PROGRAMMING. Functions What is a function? A function is a group of statements that is executed when it is called from some point of the program.
Current Assignments Homework 3 is due tonight. Iteration and basic functions. Exam 1 on Monday.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
GAME102 - INTRO WHILE LOOPS G. MacKay. Fundamental Control Structures  STRAIGHT LINE  CONDITIONAL  LOOPS.
Tracing through E01, question 9 – step 1 // p02.cc P. Conrad, for CISC181 07S // Exam question for E01 #include using namespace std; void mysteryFunction(int.
Review the following : Flowcharting Variable declarations Output Input Arithmetic Calculations Conditional Statements Loops.
1 Command-Line Processing In many operating systems, command-line options are allowed to input parameters to the program SomeProgram Param1 Param2 Param3.
Recursion A function is said to be recursive if it calls itself, either directly or indirectly. void repeat( int n ) { cout
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions Jordi Cortadella Department of Computer Science.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
Function Recursion to understand recursion you must understand recursion.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
Introduction to Computer Programming
to understand recursion you must understand recursion
Recursion Chapter 12.
Intro to Programming Week # 6 Repetition Structure Lecture # 10
Dr. Bernard Chen Ph.D. University of Central Arkansas
to understand recursion you must understand recursion
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Arrays & Functions Lesson xx
Stack Memory 1 (also called Call Stack)
Stack Memory 2 (also called Call Stack)
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Stack Frames and Functions
Let’s all Repeat Together
When a function is called...
Statements and flow control
do/while Selection Structure
Recursion.
Presentation transcript:

Recursion Using Stacks

What’s Going On? int main() { // Get Input int x, y; cout << "Enter value x: "; cin >> x; // Call f y = f(x); // Print results cout << y << endl; return 0; } #include using namespace std; int f(int n) { int k, r; if (n == 0) return 0; // 0 k = n*n; // 1 r = // 2 f(n - 1); // 3 return k + r; // 4 }

What’s Going On…

What’s Going On Recursive calls to f get pushed onto stack Multiple copies of function f, each with different arguments & local variable values, and at different lines in function All computer really needs to remember for each active function call is values of arguments & local variables and the location of the next statement to be executed when control goes back “The stack" looks a little more like :

Real Stack Looks sort of like bunch of objects Several pieces of data wrapped together We can make our own stack & simulate recursive functions ourselves

Recursion to Iteration Can translate any recursive function to iterative using a stack We use our stack to model “the stack” First step… Make a class for the activation records

Activation Record to Class We need Argument(s) Local variable(s) Next line to be executed class f_record { public: int n; // f's argument int line; // current line in f int k, r; // local variables f_record(int arg):n(arg),line(0) { } };

Recursion to Iteration Keep stack of activation records for calls to f (our example function) To make call like f(5), we create f_record with n set to 5 & push it on stack Stack S; f_record call(5); S.push(call);

Loop Then loop as long as there are activation records on stack At each iteration of loop we simulate execution of next line of activation record on top of stack

Loop When activation record on top of stack comes to its return line we'll have variable for it to store returned result in // Initialize recursive function simulation: // Returned result will be stored in retval int retval; Stack S; // stack of active calls S.push(f_record(x)); // call f(x) // While there's an active function call left while(!S.isEmpty()) { f_record curr = S.pop(); int LINE = curr.line++; if (LINE == 0) { if (curr.n == 0) retval = 0; else S.push(curr); } else if (LINE == 1) { curr.k = curr.n*curr.n; S.push(curr); } else if (LINE == 2) { f_record recurse(curr.n - 1); S.push(curr); S.push(recurse); } else if (LINE == 3) { curr.r = retval; S.push(curr); } else if (LINE == 4) retval = curr.k + curr.r; } y = retval; we're simulating... int f(int n) { int k, r; if (n == 0) return 0; // 0 k = n*n; // 1 r = // 2 f(n - 1); // 3 return k + r; // 4 }

Translation Bit more code compared to original function but code is pretty easy to come up with Just have separate case for each line of function Each individual case is straightforward Thing to remember is any recursive function can be translated to iterative segment of code using a stack Procedure for doing it is pretty much what we did with our example

Ending Note Each program has stack of active function calls Differs from what we did in our recursion-to- iteration example Not just multiple copies of the same function May have many different functions Normally has fixed size Too many function calls blows the stack