Monday, March 6, We have seen how to translate void functions. What about functions that return a value such as

Size: px
Start display at page:

Download "Monday, March 6, We have seen how to translate void functions. What about functions that return a value such as"

Transcription

1 Monday, March 6, 2017 Topics for today C functions and Pep/9 subroutines Translating functions (c) Non-void functions (d) Recursive functions Reverse Engineering: Pep/9 to C C Functions and Pep/9 Subroutines (Section 6.3) Non-void functions We have seen how to translate void functions. What about functions that return a value such as A = min3 (p, q, r) B = exponent (I, N) T = abs (N) Our template for the calling and called environments needs additional steps: The calling environment reserves stack space for the value being returned 1 The called environment (subroutine) needs to put a value in there. In the following table, the three new steps are in italics and highlighted Calling environment (1) allocate stack space for result (2) allocate stack space for actual parameters (3) push actual parameters on stack (4) do CALL (10) deallocate space for parameters (11) use then deallocate returned value Called environment (subroutine) (5) allocate space for local variables (6) do action of the subroutine including.. (7) put return value on stack (8) deallocate space for local variables (9) do RET 1 Note that it would be easy, at the assembly code level, for a subprogram to return more than one value and the values returned could have different types. For example we could allocate 4 bytes for returned values and return an integer and two characters. Comp 162 Notes Page 1 of 11 March 6, 2017

2 Example 5: non-void function, parameter but no locals The abs function returns a positive number the absolute value of its parameter. Space is left on the stack for the returned value (R.V.) Function C int abs (int i) if (i<0) return -i; else return i; Pep/9 abs: ldwa 2,s ; i brge lab ; i >=0 nega ; now -i in Reg A lab: stwa 4,s ; returning value ret Call /* assume k global */ L = abs(k); subsp 2,i ; for returned value subsp 2,i ; for parameter ldwa k,d stwa 0,s ; parameter to stack call abs addsp 2,i ; finished with parameter ldwa 0,s ; the returned value stwa L,d addsp 2,i ; finished with returned value Maximum Stack R.A k R.V Comp 162 Notes Page 2 of 11 March 6, 2017

3 Example 6 non-void function with local variable and parameters. This last non-recursive example has something of everything and uses all 11 template steps. Function C int min3 (int A, int B, int C) int smallest; smallest = A; if (B<smallest) smallest = B; if (C<smallest) smallest = C; return smallest; Pep/9 min3: subsp 2,i ; local ldwa 4,s stwa 0,s ; local gets A cpwa 6,s ; compare with B brle skip ; B not smaller ldwa 6,s stwa 0,s ; smallest = B skip: cpwa 8,s ; compare with C brle skip2 ; C not smaller ldwa 8,s skip2:stwa 10,s ; return smallest addsp 2,i ret Call /* assume P,Q,R are global */ read (P,Q,R); W = min3(p,q,r); output(w); deci P,d deci Q,d deci R,d subsp 2,i ; return value subsp 6,i ; parameters ldwa P,d stwa 0,s ldwa Q,d stwa 2,s ldwa R,d stwa 4,s ; all params on stack call min3 addsp 6,i ; parameters go away ldwa 0,s stwa W,d ; return value addsp 2,i ; finished with it too deco W,d Maximum Stack smallest R.A. P Q R R.V. Comp 162 Notes Page 3 of 11 March 6, 2017

4 Recursion The calling environment for a subprogram can be (a) main program (b) another (non-main) subprogram (c) the subprogram itself. Cases (b) and (c) are really no different from (a). We just need to be particularly careful about managing the stack space. Warford's recursion example (Fig 6.25) is too complex for a first example. We will lead up to it with two simpler recursive functions: Example 7: a void function to print N stars Example 8: an int function to compute the sum of the first N integers. Example 7 recursive, void function: pstars Function C void pstars(int N) if (N>0) output('*'); pstars(n-1); Pep/9 pstars: ldwa 2,s ; parameter breq skip ; branch if zero ldbx '*',i stbx charout,d subsp 2,i ; param of recursion suba 1,i ; N-1 stwa 0,s ; is the parameter call pstars ; to print N-1 stars addsp 2,i ; get rid of parameter skip: ret Call read(count); pstars(count); deci count,d subsp 2,i ldwa count,d stwa 0,s call pstars addsp 2,i ; for parameter ; finished with parameter The two highlighted sections are the call of pstars from the main program and call of pstars from within pstars itself. Note the similarities. A trace of this program shows how the stack grows (proportional to N) until the recursion unwinds. If N is large enough, the Pep/9 stack might crash into the program instructions at the top of memory. The program is about 44 bytes. The Application Program area in the Pep/9 Comp 162 Notes Page 4 of 11 March 6, 2017

5 memory is bytes (see Chapter 4). The stack grows by 4 bytes at each recursive call so the largest value of N we could have without the stack running into the program is ( ) / 4 = Here is a modified version of pstars. It has 1000 bytes of (unused) local variables so the stack will crash into the program for smaller values of N. ( ) / 1004 = 64 pstars: subsp 1000,i ldwa 1002,s breq skip charo '*',i subsp 2,i suba 1,i stwa 0,s call pstars addsp 2,i skip: addsp 1000,i ret Here is the calling program call main stop count:.block 2 mess:.ascii "\ndone!\n\x00" main: deci count,d subsp 2,i ldwa count,d stwa 0,s call pstars addsp 2,i stro mess,d ret Here are some results of running the program the last one crashes. 10 ********** Done! 30 ****************************** Done! 60 ************************************************************ Done! 70 Comp 162 Notes Page 5 of 11 March 6, 2017

6 ************************************************ Example 8 recursive int function to find sum of first N integers Function C int sum (int N) if (N==0) return 0; else return N+sum(N-1); Pep/9 sum: ldwa 2,s ; parameter breq zerocase subsp 2,i ; space for result of recursion subsp 2,i ; space for param of recursion ldwa 6,s ; which is N suba 1,i ; minus 1 stwa 0,s ; onto the stack call sum ; compute sum(n-1) addsp 2,i ; get rid of parameter space ldwa 0,s ; here is result of recursion addsp 2,i ; get rid of that space adda 2,s ; adding N to sum(n-1) zerocase: stwa 4,s ; return result ret Call read(k); M = sum(k); deci k,d subsp 2,i ; for returned value subsp 2,i ; for parameter ldwa k,d stwa 0,s ; parameter k call sum addsp 2,i ; finished with parameter ldwa 0,s ; result of call stwa m,d addsp 2,i ; finished with result The stack growth in this case is faster than in Example 7 (6 bytes rather than 4 each time) because we are also leaving space for a return value. Recursion and iteration are equivalent - anything you can do one way you can do the other. Sometimes an algorithm is easier to devise one way then the other. Recursion has some advantages: a recursive algorithm may be shorter and more obviously correct than the equivalent iterative or a closer match to a data structure (recursive list and tree algorithms for example). However, there are time and space overheads. The following table shows the number of Pep/9 instructions executed to find the sum of the first N integers using the recursive subroutine above and an equivalent iterative one. Comp 162 Notes Page 6 of 11 March 6, 2017

7 N Recursive Iterative Increasing N by 1 requires an additional 14 instructions in the recursive version and only an additional 4 in the iterative version. Now we are ready to tackle the recursive example in the book. Figure 6.25 shows a doublyrecursive integer function, i.e., in some cases the function calls itself twice to determine the value to return. Note the checks for the non-recursive cases and the two calls in the recursive part of the function. Reverse Engineering: Pep/9 to C If we have a Pep/9 subroutine created using our checklists, we can usually do a translation back into C. Determining how the stack entries are used is important. In routines that follow our checklists, the stack regions are Local Variables Return Address (2 bytes) Parameters Space for returned value(s) Comp 162 Notes Page 7 of 11 March 6, 2017

8 Here is our first example. Line 1 mystery: subsp 2,i 2 ldwa 4,s 3 stwa 0,s 4 top: breq done 5 ldbx 6,s 6 stbx charout,d 7 ldwa 0,s 8 suba 1,i 9 stwa 0,s 10 br top 11 done: addsp 2,i 12 ret Our construction of the corresponding C function begins with a skeleton form using the name?? mystery ( ) We see (Line 1) that 2 bytes are allocated for local variables (these bytes are deallocated on line 11). References to this part of the stack (Lines 3, 7 and 9) use word operations so we assume this is a single integer variable rather than two character variables. Thus we have?? mystery () int temp; The return address is at 2,s so references to locations further down the stack than that are to parameters and return value space. The subroutine does not write to any of these locations so does not return a value so is a void function. void mystery () int temp; The parameter at 4,s is accessed using a word instruction (Line 2) so occupies 4,s and 5,s. The parameter at 6,s is accessed using a byte operation (Line 5). We can fill in the parameter types. void mystery (int A; char B) int temp; The body of the subroutine is an assignment of the parameter value to the local variable (Lines 2 and 3) followed by a loop (Lines 4-10). Comp 162 Notes Page 8 of 11 March 6, 2017

9 void mystery (int A; char B) int temp; temp = A; while ( ) All that remains is to fill out the condition and loop body void mystery (int A; char B) int temp; temp = A; while (temp!= 0 ) printf( %c,b); temp--; Thus a call of mystery(12, t ) will print 12 t s. Reading There is very little discussion of simple non-void functions in the text. Comp 162 Notes Page 9 of 11 March 6, 2017

10 Review Questions 1. We know that in the Fibonacci sequence, most terms are the sum of the two previous terms so why can t we define fib(n) as fib(n): return fib(n-1)+fib(n-2) 2. How can a Pep/9 non-void subroutine return, for example, two integers as its result? 3. When we are reverse-engineering a subroutine, how can we distinguish between the translations of int X (int, int, int) and void X (int,int,int,int) Both will have 8 bytes of space reserved by the calling environment. 4. A student claims that the following prints N in binary for non-negative N. Is she right? Printbin(N): if n=1 print ( 1 ) Else if odd(n) printbin(n/2); print ( 1 ) Else printbin(n/2); print ( 0 ) 5. Why is a recursive version of the Fibonacci function inefficient for large N? Comp 162 Notes Page 10 of 11 March 6, 2017

11 Review Answers 1. There is no non-recursive or base case. We need something like Fib(N): if N<3 return 1 else return fib(n-1)+fib(n-2) 2. The calling environment leaves room for 4 bytes of result on the stack and the subroutine puts two integers in those locations. 3. The former will have a word that is only written to, never read from, this represents the returned value. 4. Almost. If N is zero, there is infinite recursion and nothing printed 5. It makes repeated calls with the same parameter. Comp 162 Notes Page 11 of 11 March 6, 2017

Monday, March 27, 2017

Monday, March 27, 2017 Monday, March 27, 2017 Topics for today Indexed branching Implementation of switch statement Reusable subroutines Indexed branching It turns out that arrays are useful in translating other language constructs,

More information

Wednesday, February 28, 2018

Wednesday, February 28, 2018 Wednesday, February 28, 2018 Topics for today C functions and Pep/9 subroutines Introduction Location of subprograms in a program Translating functions (a) Void functions (b) Void functions with parameters

More information

Wednesday, September 27, 2017

Wednesday, September 27, 2017 Wednesday, September 27, 2017 Topics for today Chapter 6: Mapping High-level to assembly-level The Pep/9 run-time stack (6.1) Stack-relative addressing (,s) SP manipulation Stack as scratch space Global

More information

Wednesday, March 14, 2018

Wednesday, March 14, 2018 Wednesday, March 14, 2018 Topics for today Arrays and Indexed Addressing Arrays as parameters of functions Multi-dimensional arrays Option A: Space-minimal solution Option B: Iliffe vectors Array bound

More information

Monday, March 9, 2015

Monday, March 9, 2015 Monday, March 9, 2015 Topics for today C functions and Pep/8 subroutines Passing parameters by reference Globals Locals More reverse engineering: Pep/8 to C Representation of Booleans C Functions and Pep/8

More information

Monday, October 17, 2016

Monday, October 17, 2016 Monday, October 17, 2016 Topics for today C functions and Pep/8 subroutines Passing parameters by reference Globals Locals Reverse Engineering II Representation of Booleans C Functions and Pep/8 Subroutines

More information

Monday, March 13, 2017

Monday, March 13, 2017 Monday, March 13, 2017 Topics for today Arrays and Indexed Addressing Global arrays Local arrays Buffer exploit attacks Arrays and indexed addressing (section 6.4) So far we have looked at scalars (int,

More information

Wednesday, February 15, 2017

Wednesday, February 15, 2017 Wednesday, February 15, 2017 Topics for today Before and after assembly: Macros, Linkers Overview of Chapter 6 Branching Unconditional Status bits and branching If statements While statements The V and

More information

Monday, October 24, 2016

Monday, October 24, 2016 Monday, October 24, 2016 Topics for today Arrays and Indexed Addressing Arrays as parameters of functions Multi-dimensional arrays Option A: Space-minimal solution Option B: Iliffe vectors Array bound

More information

Wednesday, March 12, 2014

Wednesday, March 12, 2014 Wednesday, March 12, 2014 Topics for today Solutions to HW #3 Arrays and Indexed Addressing Global arrays Local arrays Buffer exploit attacks Solutions to Homework #3 1. deci N,d < (a) N not defined lda

More information

Wednesday, September 20, 2017

Wednesday, September 20, 2017 Wednesday, September 20, 2017 Topics for today More high-level to Pep/9 translations Compilers and Assemblers How assemblers work Symbol tables ILC Pass 1 algorithm, Error checking Pass 2 Immediate mode

More information

Wednesday, February 7, 2018

Wednesday, February 7, 2018 Wednesday, February 7, 2018 Topics for today The Pep/9 memory Four example programs The loader The assembly language level (Chapter 5) Symbolic Instructions Assembler directives Immediate mode and equate

More information

Wednesday, March 29, Implementation of sets in an efficient manner illustrates some bit-manipulation ideas.

Wednesday, March 29, Implementation of sets in an efficient manner illustrates some bit-manipulation ideas. Wednesday, March 29, 2017 Topics for today Sets: representation and manipulation using bits Dynamic memory allocation Addressing mode summary Sets Implementation of sets in an efficient manner illustrates

More information

Monday, September 28, 2015

Monday, September 28, 2015 Monda, September 28, 2015 Topics for toda Chapter 6: Mapping High-level to assembl-level The Pep/8 run-time stack (6.1) Stack-relative addressing (,s) SP manipulation Stack as scratch space Global variables

More information

Monday, February 16, 2015

Monday, February 16, 2015 Monday, February 16, 2015 Topics for today How assemblers work Symbol tables ILC Pass 1 algorithm, Error checking Pass 2 Immediate mode and equate Assembler variants: Disassembler, Cross assembler Macros

More information

Wednesday, September 21, 2016

Wednesday, September 21, 2016 Wednesday, September 21, 2016 Topics for today More high-level to translations Compilers and Assemblers How assemblers work Symbol tables ILC Pass 1 algorithm, Error checking Pass 2 Immediate mode and

More information

Wednesday, February 19, 2014

Wednesday, February 19, 2014 Wednesda, Februar 19, 2014 Topics for toda Solutions to HW #2 Topics for Eam #1 Chapter 6: Mapping High-level to assembl-level The Pep/8 run-time stack Stack-relative addressing (,s) SP manipulation Stack

More information

Wednesday, October 17, 2012

Wednesday, October 17, 2012 Wednesday, October 17, 2012 Topics for today Arrays and Indexed Addressing Arrays as parameters of functions Multi-dimensional arrays Indexed branching Implementation of switch statement Arrays as parameters

More information

Monday, November 7, Structures and dynamic memory

Monday, November 7, Structures and dynamic memory Monday, November 7, 2016 Topics for today Structures Structures and dynamic memory Grammars and Languages (Chapter 7) String generation Parsing Regular languages Structures We have seen one composite data

More information

CSC 221: Computer Organization, Spring 2009

CSC 221: Computer Organization, Spring 2009 1 of 7 4/17/2009 10:52 AM Overview Schedule Resources Assignments Home CSC 221: Computer Organization, Spring 2009 Practice Exam 2 Solutions The exam will be open-book, so that you don't have to memorize

More information

Wednesday, October 4, Optimizing compilers source modification Optimizing compilers code generation Your program - miscellaneous

Wednesday, October 4, Optimizing compilers source modification Optimizing compilers code generation Your program - miscellaneous Wednesday, October 4, 2017 Topics for today Code improvement Optimizing compilers source modification Optimizing compilers code generation Your program - miscellaneous Optimization Michael Jackson Donald

More information

Monday, October 26, 2015

Monday, October 26, 2015 Monday, October 26, 2015 Topics for today Indexed branching Implementation of switch statement Reusable subroutines Indexed branching It turns out that arrays are useful in translating other language constructs,

More information

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

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Functions CS10001: Programming & Data Structures Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Recursion A process by which a function calls itself

More information

Monday, April 9, 2018

Monday, April 9, 2018 Monday, April 9, 208 Topics for today Grammars and Languages (Chapter 7) Finite State Machines Semantic actions Code generation Overview Finite State Machines (see 7.2) If a language is regular (Type 3)

More information

Wednesday, November 15, 2017

Wednesday, November 15, 2017 Wednesday, November 15, 2017 Topics for today Code generation Synthesis Algorithm 5: tree to code Optimizations Code generation Algorithm 5: generating assembly code Visiting all the nodes in a linked

More information

MIPS Programming. A basic rule is: try to be mechanical (that is, don't be "tricky") when you translate high-level code into assembler code.

MIPS Programming. A basic rule is: try to be mechanical (that is, don't be tricky) when you translate high-level code into assembler code. MIPS Programming This is your crash course in assembler programming; you will teach yourself how to program in assembler for the MIPS processor. You will learn how to use the instruction set summary to

More information

Wednesday, April 16, 2014

Wednesday, April 16, 2014 Wednesday, pril 16, 2014 Topics for today Homework #5 solutions Code generation nalysis lgorithm 4: infix to tree Synthesis lgorithm 5: tree to code Optimization HW #5 solutions 1. lda 0,i ; for sum of

More information

Wednesday, April 19, 2017

Wednesday, April 19, 2017 Wednesday, April 19, 2017 Topics for today Process management (Chapter 8) Loader Traps Interrupts, Time-sharing Storage management (Chapter 9) Main memory (1) Uniprogramming (2) Fixed-partition multiprogramming

More information

Monday, February 11, 2013

Monday, February 11, 2013 Monday, February 11, 2013 Topics for today The Pep/8 memory Four example programs The loader The assembly language level (Chapter 5) Symbolic Instructions Assembler directives Immediate mode and equate

More information

Wednesday, April 22, 2015

Wednesday, April 22, 2015 Wednesday, April 22, 2015 Topics for today Topics for Exam 3 Process management (Chapter 8) Loader Traps Interrupts, Time-sharing Storage management (Chapter 9) Main memory (1) Uniprogramming (2) Fixed-partition

More information

Wednesday, November 8, 2017

Wednesday, November 8, 2017 Wednesday, November 8, 207 Topics for today Grammars and Languages (hapter 7) Finite State Machines Semantic actions ode generation - Overview Finite State Machines (see 7.2) If a language is regular (Type

More information

Wednesday, April

Wednesday, April Wednesday, April 9. 2014 Topics for today Addressing mode summary Structures Structures and dynamic memory Grammars and Languages (Chapter 7) String generation Parsing Regular languages Summary of addressing

More information

Low-level software. Components Circuits Gates Transistors

Low-level software. Components Circuits Gates Transistors QUIZ Pipelining A computer pipeline has 4 processors, as shown above. Each processor takes 15 ms to execute, and each instruction must go sequentially through all 4 processors. A program has 10 instructions.

More information

QUIZ. Name all the 4 parts of the fetch-execute cycle.

QUIZ. Name all the 4 parts of the fetch-execute cycle. QUIZ Name all the 4 parts of the fetch-execute cycle. 1 Solution Name all the 4 parts of the fetch-execute cycle. 2 QUIZ Name two fundamental differences between magnetic drives and optical drives: 3 QUIZ

More information

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

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others 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

More information

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

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 13: Recursion Sandeep Manjanna, Summer 2015 Announcements Final exams : 26 th of June (2pm to 5pm) @ MAASS 112 Assignment 4 is posted and Due on 29 th of June

More information

Copyright The McGraw-Hill Companies, Inc. Persion required for reproduction or display. What is Recursion?

Copyright The McGraw-Hill Companies, Inc. Persion required for reproduction or display. What is Recursion? Chapter 17 Recursion Original slides from Gregory Byrd, North Carolina State University Modified slides by Chris Wilcox, Colorado State University! A recursive function is one that solves its task by calling

More information

Subprograms, Subroutines, and Functions

Subprograms, Subroutines, and Functions Subprograms, Subroutines, and Functions Subprograms are also called subroutines, functions, procedures and methods. A function is just a subprogram that returns a value; say Y = SIN(X). In general, the

More information

We cover recursion in 150. Why do it again in 151?

We cover recursion in 150. Why do it again in 151? Recursion We cover recursion in 150. Why do it again in 151? First, good solutions to problems are often recursive. Here is a quick way to sort a list of objects: split the list in half, recursively sort

More information

QUIZ. Name all the 4 parts of the fetch-execute cycle.

QUIZ. Name all the 4 parts of the fetch-execute cycle. QUIZ Name all the 4 parts of the fetch-execute cycle. 1 Solution Name all the 4 parts of the fetch-execute cycle. 2 QUIZ Name two fundamental differences between magnetic drives and optical drives: 3 Solution

More information

Announcements. Class 7: Intro to SRC Simulator Procedure Calls HLL -> Assembly. Agenda. SRC Procedure Calls. SRC Memory Layout. High Level Program

Announcements. Class 7: Intro to SRC Simulator Procedure Calls HLL -> Assembly. Agenda. SRC Procedure Calls. SRC Memory Layout. High Level Program Fall 2006 CS333: Computer Architecture University of Virginia Computer Science Michele Co Announcements Class 7: Intro to SRC Simulator Procedure Calls HLL -> Assembly Homework #2 Due next Wednesday, Sept.

More information

APCS-AB: Java. Recursion in Java December 12, week14 1

APCS-AB: Java. Recursion in Java December 12, week14 1 APCS-AB: Java Recursion in Java December 12, 2005 week14 1 Check point Double Linked List - extra project grade Must turn in today MBCS - Chapter 1 Installation Exercises Analysis Questions week14 2 Scheme

More information

Wednesday, September 13, Chapter 4

Wednesday, September 13, Chapter 4 Wednesday, September 13, 2017 Topics for today Introduction to Computer Systems Static overview Operation Cycle Introduction to Pep/9 Features of the system Operational cycle Program trace Categories of

More information

Chapter 17 Recursion

Chapter 17 Recursion Chapter 17 Recursion What is Recursion? A recursive function is one that solves its task by calling itself on smaller pieces of data. Similar to recurrence function in mathematics. Like iteration -- can

More information

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Reading for this lecture: Carrano, Chapter 2 Copy constructor, destructor, operator=

More information

What is Recursion? Chapter 17 Recursion. Executing RunningSum. High-Level Example: Binary Search

What is Recursion? Chapter 17 Recursion. Executing RunningSum. High-Level Example: Binary Search Chapter 17 Recursion Original slides from Gregory Byrd, North Carolina State University Modified slides by Chris Wilcox, Colorado State University! A recursive function is one that solves its task by calling

More information

Search,Sort,Recursion

Search,Sort,Recursion Search,Sort,Recursion Searching, Sorting and Recursion Searching Linear Search Inserting into an Array Deleting from an Array Selection Sort Bubble Sort Binary Search Recursive Binary Search Searching

More information

STUDENT LESSON A9 Recursion

STUDENT LESSON A9 Recursion STUDENT LESSON A9 Recursion Java Curriculum for AP Computer Science, Student Lesson A9 1 STUDENT LESSON A9 Recursion INTRODUCTION: Recursion is the process of a method calling itself as part of the solution

More information

Procedures and Stacks

Procedures and Stacks Procedures and Stacks Daniel Sanchez Computer Science & Artificial Intelligence Lab M.I.T. March 15, 2018 L10-1 Announcements Schedule has shifted due to snow day Quiz 2 is now on Thu 4/12 (one week later)

More information

Calling Conventions. Hakim Weatherspoon CS 3410, Spring 2012 Computer Science Cornell University. See P&H 2.8 and 2.12

Calling Conventions. Hakim Weatherspoon CS 3410, Spring 2012 Computer Science Cornell University. See P&H 2.8 and 2.12 Calling Conventions Hakim Weatherspoon CS 3410, Spring 2012 Computer Science Cornell University See P&H 2.8 and 2.12 Goals for Today Calling Convention for Procedure Calls Enable code to be reused by allowing

More information

Assembly Programming (III) Lecturer: Sri Parameswaran Notes by: Annie Guo Dr. Hui Wu

Assembly Programming (III) Lecturer: Sri Parameswaran Notes by: Annie Guo Dr. Hui Wu Assembly Programming (III) Lecturer: Sri Parameswaran Notes by: Annie Guo Dr. Hui Wu 1 Lecture overview Stack and stack operations Functions and function calls Calling conventions 2 Stack What is stack?

More information

LOW-LEVEL PROGRAMMING LANAGUAGES AND PSEUDOCODE. Introduction to Computer Engineering 2015 Spring by Euiseong Seo

LOW-LEVEL PROGRAMMING LANAGUAGES AND PSEUDOCODE. Introduction to Computer Engineering 2015 Spring by Euiseong Seo LOW-LEVEL PROGRAMMING LANAGUAGES AND PSEUDOCODE Introduction to Computer Engineering 2015 Spring by Euiseong Seo Where are we? Chapter 1: The Big Picture Chapter 2: Binary Values and Number Systems Chapter

More information

Chapter 17 Recursion

Chapter 17 Recursion Chapter 17 Recursion What is Recursion? A recursive function is one that solves its task by calling itself on smaller pieces of data. Similar to recurrence relation in mathematics. Sometimes recursion

More information

Recursive Definitions

Recursive Definitions Recursion Objectives Explain the underlying concepts of recursion Examine recursive methods and unravel their processing steps Explain when recursion should and should not be used Demonstrate the use of

More information

def F a c t o r i a l ( n ) : i f n == 1 : return 1 else : return n F a c t o r i a l ( n 1) def main ( ) : print ( F a c t o r i a l ( 4 ) )

def F a c t o r i a l ( n ) : i f n == 1 : return 1 else : return n F a c t o r i a l ( n 1) def main ( ) : print ( F a c t o r i a l ( 4 ) ) 116 4.5 Recursion One of the most powerful programming techniques involves a function calling itself; this is called recursion. It is not immediately obvious that this is useful; take that on faith for

More information

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano Chapter 2 Recursion: The Mirrors Multiple Choice Questions 1. In a recursive solution, the terminates the recursive processing. a) local environment b) pivot item c) base case d) recurrence relation 2.

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

A rubric for programming assignments

A rubric for programming assignments Fall 2012 Comp 162 Peter Smith A rubric for programming assignments Generally, half the points for a program assignment are for the Correctness of the program with respect to the specification. The other

More information

There are some situations in which recursion can be massively inefficient. For example, the standard Fibonacci recursion Fib(n) = Fib(n-1) + Fib(n-2)

There are some situations in which recursion can be massively inefficient. For example, the standard Fibonacci recursion Fib(n) = Fib(n-1) + Fib(n-2) Dynamic Programming There are some situations in which recursion can be massively inefficient. For example, the standard Fibonacci recursion Fib(n) = Fib(n-1) + Fib(n-2) computes the same values over and

More information

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

Announcements. Recursion and why study it. Recursive programming. Recursion basic idea Announcements Recursion and why study it Tutoring schedule updated Do you find the sessions helpful? Midterm exam 1: Tuesday, April 11, in class Scope: will cover up to recursion Closed book but one sheet,

More information

Recursion. Chapter 17 CMPE13. Cyrus Bazeghi

Recursion. Chapter 17 CMPE13. Cyrus Bazeghi Recursion Chapter 17 CMPE13 Cyrus Bazeghi What is Recursion? A recursive function is one that solves its task by calling itself on smaller pieces of data. Similar to recurrence function in mathematics.

More information

Extra-credit QUIZ Pipelining -due next time-

Extra-credit QUIZ Pipelining -due next time- QUIZ Pipelining A computer pipeline has 4 processors, as shown above. Each processor takes 15 ms to execute, and each instruction must go sequentially through all 4 processors. A program has 10 instructions.

More information

What Is a Function? Illustration of Program Flow

What Is a Function? Illustration of Program Flow What Is a Function? A function is, a subprogram that can act on data and return a value Each function has its own name, and when that name is encountered, the execution of the program branches to the body

More information

Using the MIPS Calling Convention. Recursive Functions in Assembly. CS 64: Computer Organization and Design Logic Lecture #10 Fall 2018

Using the MIPS Calling Convention. Recursive Functions in Assembly. CS 64: Computer Organization and Design Logic Lecture #10 Fall 2018 Using the MIPS Calling Convention Recursive Functions in Assembly CS 64: Computer Organization and Design Logic Lecture #10 Fall 2018 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB Administrative Lab

More information

Assembly Programming (III)

Assembly Programming (III) Assembly Programming (III) Lecturer: Annie Guo S2, 2006 COMP9032 Week6 1 Lecture Overview Stack and stack operations Functions and function calls Calling conventions S2, 2006 COMP9032 Week6 2 What is stack?

More information

Monday, April 14, 2014

Monday, April 14, 2014 Monday, April 14, 2014 Topics for today Grammars and Languages (Chapter 7) Finite State Machines Semantic actions Code generation - Overview Analysis Algorithm 1: evaluation of postfix Algorithm 2: infix

More information

Anne Bracy CS 3410 Computer Science Cornell University

Anne Bracy CS 3410 Computer Science Cornell University Anne Bracy CS 3410 Computer Science Cornell University The slides are the product of many rounds of teaching CS 3410 by Professors Weatherspoon, Bala, Bracy, McKee, and Sirer. See P&H 2.8 and 2.12, and

More information

CS 3410 Ch 7 Recursion

CS 3410 Ch 7 Recursion CS 3410 Ch 7 Recursion Sections Pages 7.1-7.4, 7.7 93-319, 333-336 7.1 Introduction 1. A recursive method is a method that either directly or indirectly makes a call to itself. [Weiss]. It does this by

More information

Monday, April 15, We will lead up to the Analysis and Synthesis algorithms involved by first looking at three simpler ones.

Monday, April 15, We will lead up to the Analysis and Synthesis algorithms involved by first looking at three simpler ones. Monday, pril 15, 2013 Topics for today Code generation nalysis lgorithm 1: evaluation of postfix lgorithm 2: infix to postfix lgorithm 3: evaluation of infix lgorithm 4: infix to tree Synthesis lgorithm

More information

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

Standard Version of Starting Out with C++, 4th Edition. Chapter 19 Recursion. Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion Copyright 2003 Scott/Jones Publishing Topics 19.1 Introduction to Recursion 19.2 The Recursive Factorial Function 19.3 The Recursive

More information

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1 COMP 202 Recursion CONTENTS: Recursion COMP 202 - Recursion 1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself COMP 202 - Recursion

More information

CS 216 Exam 1 Fall SOLUTION

CS 216 Exam 1 Fall SOLUTION CS 216 Exam 1 Fall 2004 - SOLUTION Name: Lab Section: Email Address: Student ID # This exam is closed note, closed book. You will have an hour and fifty minutes total to complete the exam. You may NOT

More information

Recursion(int day){return Recursion(day += 1);} Comp Sci 1575 Data Structures. Recursive design. Convert loops to recursion

Recursion(int day){return Recursion(day += 1);} Comp Sci 1575 Data Structures. Recursive design. Convert loops to recursion Recursion(int day){return Recursion(day += 1);} Comp Sci 1575 Data Structures Outline 1 2 Solution 2: calls 3 Implementation To create recursion, you must create recursion. How to a recursive algorithm

More information

Subprograms: Arguments

Subprograms: Arguments Subprograms: Arguments ICS312 Machine-Level and Systems Programming Henri Casanova (henric@hawaii.edu) Activation Records The stack is useful to store and rieve urn addresses, transparently managed via

More information

Data Structures And Algorithms

Data Structures And Algorithms Data Structures And Algorithms Recursion Eng. Anis Nazer First Semester 2016-2017 Recursion Recursion: to define something in terms of itself Example: factorial n!={ 1 n=0 n (n 1)! n>0 Recursion Example:

More information

ECE 375 Computer Organization and Assembly Language Programming Winter 2018 Solution Set #2

ECE 375 Computer Organization and Assembly Language Programming Winter 2018 Solution Set #2 ECE 375 Computer Organization and Assembly Language Programming Winter 2018 Set #2 1- Consider the internal structure of the pseudo-cpu discussed in class augmented with a single-port register file (i.e.,

More information

School of Computer Science Introduction to Algorithms and Programming Winter Midterm Examination # 1 Wednesday, February 11, 2015

School of Computer Science Introduction to Algorithms and Programming Winter Midterm Examination # 1 Wednesday, February 11, 2015 Page 1 of 8 School of Computer Science 60-141-01 Introduction to Algorithms and Programming Winter 2015 Midterm Examination # 1 Wednesday, February 11, 2015 Marking Exemplar Duration of examination: 75

More information

Low-Level Programming Languages and Pseudocode

Low-Level Programming Languages and Pseudocode Chapter 6 Low-Level Programming Languages and Pseudocode Chapter Goals List the operations that a computer can perform Describe the important features of the Pep/8 virtual machine Distinguish between immediate

More information

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

Recursion. Comp Sci 1575 Data Structures. Introduction. Simple examples. The call stack. Types of recursion. Recursive programming Recursion Comp Sci 1575 Data Structures Outline 1 2 3 4 Definitions To understand, you must understand. Familiar of recursive definitions Natural numbers are either: n+1, where n is a natural number 1

More information

Storage in Programs. largest. address. address

Storage in Programs. largest. address. address Storage in rograms Almost all operand storage used by programs is provided by memory. Even though registers are more efficiently accessed by instructions, there are too few registers to hold the stored

More information

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

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub I2204- Imperative Programming Schedule 08h00-09h40

More information

recursive algorithms 1

recursive algorithms 1 COMP 250 Lecture 11 recursive algorithms 1 Oct. 2, 2017 1 Example 1: Factorial (iterative)! = 1 2 3 1 factorial( n ){ // assume n >= 1 result = 1 for (k = 2; k

More information

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

Recursion. Let s start by looking at some problems that are nicely solved using recursion. First, let s look at generating The Fibonacci series. Recursion The programs we have discussed so far have been primarily iterative and procedural. Code calls other methods in a hierarchical manner. For some problems, it is very useful to have the methods

More information

COSC 243. Assembly Language Techniques. Lecture 9. COSC 243 (Computer Architecture)

COSC 243. Assembly Language Techniques. Lecture 9. COSC 243 (Computer Architecture) COSC 243 Assembly Language Techniques 1 Overview This Lecture Source Handouts Next Lectures Memory and Storage Systems 2 Parameter Passing In a high level language we don t worry about the number of parameters

More information

COMP 303 Computer Architecture Lecture 3. Comp 303 Computer Architecture

COMP 303 Computer Architecture Lecture 3. Comp 303 Computer Architecture COMP 303 Computer Architecture Lecture 3 Comp 303 Computer Architecture 1 Supporting procedures in computer hardware The execution of a procedure Place parameters in a place where the procedure can access

More information

8/2/10. Looking for something COMP 10 EXPLORING COMPUTER SCIENCE. Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE

8/2/10. Looking for something COMP 10 EXPLORING COMPUTER SCIENCE. Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE Looking for something COMP 10 EXPLORING COMPUTER SCIENCE Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE Searching algorithms Linear search Complexity Sorting algorithms

More information

CSE 143 Lecture 10. Recursion

CSE 143 Lecture 10. Recursion CSE 143 Lecture 10 Recursion slides created by Marty Stepp and Alyssa Harding http://www.cs.washington.edu/143/ Recursion Iteration: a programming technique in which you describe actions to be repeated

More information

Stack Frames. Compilers use the stack: to store the to to a subroutine for storage of declared in the subroutine and a place to

Stack Frames. Compilers use the stack: to store the to to a subroutine for storage of declared in the subroutine and a place to Stack Frames EE 357 Unit 8 Stack Frames Compilers use the stack: to store the to to a subroutine for storage of declared in the subroutine and a place to Every call to a subroutine will create a data structure

More information

More Complicated Recursion CMPSC 122

More Complicated Recursion CMPSC 122 More Complicated Recursion CMPSC 122 Now that we've gotten a taste of recursion, we'll look at several more examples of recursion that are special in their own way. I. Example with More Involved Arithmetic

More information

CSC 1600 Memory Layout for Unix Processes"

CSC 1600 Memory Layout for Unix Processes CSC 16 Memory Layout for Unix Processes" 1 Lecture Goals" Behind the scenes of running a program" Code, executable, and process" Memory layout for UNIX processes, and relationship to C" : code and constant

More information

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa Functions Autumn Semester 2009 Programming and Data Structure 1 Courtsey: University of Pittsburgh-CSD-Khalifa Introduction Function A self-contained program segment that carries out some specific, well-defined

More information

See P&H 2.8 and 2.12, and A.5-6. Prof. Hakim Weatherspoon CS 3410, Spring 2015 Computer Science Cornell University

See P&H 2.8 and 2.12, and A.5-6. Prof. Hakim Weatherspoon CS 3410, Spring 2015 Computer Science Cornell University See P&H 2.8 and 2.12, and A.5-6 Prof. Hakim Weatherspoon CS 3410, Spring 2015 Computer Science Cornell University Upcoming agenda PA1 due yesterday PA2 available and discussed during lab section this week

More information

Binding and Storage. COMP 524: Programming Language Concepts Björn B. Brandenburg. The University of North Carolina at Chapel Hill

Binding and Storage. COMP 524: Programming Language Concepts Björn B. Brandenburg. The University of North Carolina at Chapel Hill Binding and Storage Björn B. Brandenburg The University of North Carolina at Chapel Hill Based in part on slides and notes by S. Olivier, A. Block, N. Fisher, F. Hernandez-Campos, and D. Stotts. What s

More information

The University of North Carolina at Chapel Hill. Comp 411 Computer Organization Spring Problem Set #3 Solution Set

The University of North Carolina at Chapel Hill. Comp 411 Computer Organization Spring Problem Set #3 Solution Set Problem 1. Compiler Appreciation The University of North Carolina at Chapel Hill Comp 411 Computer Organization Spring 2012 Problem Set #3 Solution Set There are many solutions to these problems. My solutions

More information

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57 Comp 11 Lectures Mike Shah Tufts University June 26, 2017 Mike Shah (Tufts University) Comp 11 Lectures June 26, 2017 1 / 57 Please do not distribute or host these slides without prior permission. Mike

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter

More information

Loops / Repetition Statements

Loops / Repetition Statements Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for

More information

NCS 301 DATA STRUCTURE USING C

NCS 301 DATA STRUCTURE USING C NCS 301 DATA STRUCTURE USING C Unit-1 Part-2 Recursion Hammad Mashkoor Lari Assistant Professor Allenhouse Institute of Technology www.ncs301ds.wordpress.com Introduction Recursion is defined as defining

More information

Functions in C. Memory Allocation in C. C to LC3 Code generation. Next.. Complete and submit C to LC3 code generation. How to handle function calls?

Functions in C. Memory Allocation in C. C to LC3 Code generation. Next.. Complete and submit C to LC3 code generation. How to handle function calls? Memory Allocation in C Functions in C Global data pointer: R4 Global and static variables Specify positive offsets Frame pointer: Points to current code block Negative offset Stack Pointer: Top of stack

More information

Computer Architecture and System Software Lecture 06: Assembly Language Programming

Computer Architecture and System Software Lecture 06: Assembly Language Programming Computer Architecture and System Software Lecture 06: Assembly Language Programming Instructor: Rob Bergen Applied Computer Science University of Winnipeg Announcements Assignment 3 due thursday Midterm

More information