lec4_compile_2_execute

# jr ra elec 5200 0016200 001 lecture 4 procedure b jr

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: xample: A Recursive Procedure Int { fact (n) if (n < 1) else return (1); return (n * fact (n-1)); } This procedure returns factorial of integer n, i.e., n! = n × (n-1) × (n-2) × . . . × 2 × 1 = n × (n-1)! Boundary case, 0! = 1 Spring 2014, Feb 10 . . . Spring ELEC 5200-001/6200-001 Lecture 4 26 Flowchart of fact Flowchart fact n ≥ 0 n < 1 Yes v(n) = 1 No v(n) = n * v(n­1) Return v(n) Spring 2014, Feb 10 . . . Spring ELEC 5200-001/6200-001 Lecture 4 27 Example: Compute 4! n = 4 Main program calls fact, \$a0 = 4 Returns \$v0 = \$v0 * \$a0 = 24 v(4) = 4 * v(3) fact calls fact, \$a0 = 3 v(3) = 3 * v(2) fact calls fact, \$a0 = 2 v(2) = 2 * v(1) fact calls fact, \$a0 = 1 v(1) = 1 * v(0) fact calls fact, \$a0 = 0 Returns \$v0 = \$v0 * \$a0 = 6 Returns \$v0 = \$v0 * \$a0 = 2 Returns \$v0 = \$v0 * \$a0 = 1 Returns \$v0 = 1 v(0) = 1 Spring 2014, Feb 10 . . . Spring ELEC 5200-001/6200-001 Lecture 4 28 What to Save? Recursive procedure will call itself. So, – will reuse return address register \$ra – will change argument register \$a0 These two registers mu...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online