13-recursive_programming

# Example printbinary7 prints 111 example printbinary12

• Notes
• 16

This preview shows 6 out of 11 pages.

Example:  printBinary(7)  prints 111 Example:  printBinary(12)  prints 1100 Example:  printBinary(42)  prints 101010 Write the method recursively and without using any loops. plac e 1 0 1 3 2 1 6 8 4 2 1 valu e 4 2 1 0 1 0 1 0

Subscribe to view the full document.

7 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
8 printBinary  solution // Prints the given integer's binary representation. // Precondition: n >= 0 public static void printBinary(int n) { if (n < 2) { // base case; same as base 10 System.out.println(n); } else { // recursive case; break number apart printBinary(n / 2); printBinary(n % 2); } } Can we eliminate the precondition and deal with negatives?

Subscribe to view the full document.

9 printBinary  solution 2 // Prints the given integer's binary representation. public static void printBinary(int n) { if (n < 0) { // recursive case for negative numbers System.out.print("-"); printBinary(-n); } else if (n < 2) { // base case; same as base 10 System.out.println(n); } else { // recursive case; break number apart printBinary(n / 2); printBinary(n % 2); } }
10 Exercise Write a recursive method  isPalindrome  accepts a  String   and returns  true  if it reads the same forwards as backwards.

Subscribe to view the full document.

You've reached the end of this preview.
• Spring '08
• SR
• Computer Science, Binary numeral system, Marty Stepp, recursive case

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern