11-recursive_programming

# 11-recursive_programming - CSE 143 Lecture 11 Recursive...

This preview shows pages 1–4. Sign up to view the full content.

1 CSE 143 Lecture 11 Recursive Programming slides created by Marty Stepp http://www.cs.washington.edu/143/ 2 Decimal Numbers • A visual review of decimal numbers: – We get 348 by adding powers of 10 348 = 300 + 40 + 8 = 3 × 10 2 + 4 × 10 1 + 8 × 10 0 • That’s why the decimal system is base 10

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 3 Binary Numbers • Binary is exactly the same, but base 2 Decimal Binary Sum 0 0 0 × 2 0 1 1 1 × 2 0 2 10 1 × 2 1 + 0 × 2 0 3 11 1 × 2 1 + 1 × 2 0 4 100 1 × 2 2 + 0 × 2 1 + 0 × 2 0 5 101 1 × 2 2 + 0 × 2 1 + 1 × 2 0 6 110 1 × 2 2 + 1 × 2 1 + 0 × 2 0 7 111 1 × 2 2 + 1 × 2 1 + 1 × 2 0 8 1000 1 × 2 3 + 0 × 2 2 + 0 × 2 1 + 0 × 2 0 4 Exercise • Write a recursive method printBinary that accepts an integer and prints that number's representation in binary (base 2) . – Example: printBinary(7) prints 111 – Example: printBinary(12) prints 1100 – Example: printBinary(42) prints 101010 – Write the method recursively and without using any loops. place 10 1 32 16 8 4 2 1 value 4 2 1 0 1 0 1 0
3 5 Case analysis • Recursion is about solving a small piece of a large problem. – What is 69743 in binary? • Do we know anything about its representation in binary? – Case analysis: • What is/are easy numbers to print in binary? • Can we express a larger number in terms of a smaller number(s)? – Suppose we are examining some arbitrary integer N . • if N 's binary representation is 1001010101 1 •(N / 2) 's binary representation is 1001010101 •(N % 2) 's binary representation is 1 6 printBinary solution // Prints the given integer's binary representation. // Precondition: n >= 0

This preview has intentionally blurred sections. Sign up to view the full version.

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

## This note was uploaded on 09/29/2010 for the course CSE 143 taught by Professor Sr during the Spring '08 term at University of Washington.

### Page1 / 9

11-recursive_programming - CSE 143 Lecture 11 Recursive...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online