recExerciseSolnFall10

recExerciseSolnFall10 - else return s.charAt(s.length() -...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Recursion Exercises CSE205 First Name (Print)___________________ Last Name _________________ Lecture __________ For each of the following problems write a recursive method. 1. Write a recursive method int power(int i, int j) which determines the result of i j where j >= 0. public int powerR(int i, int j) { if (j == 0) return 1; // i 0 = 1 for any i else return powerR(i, j-1) * i; // i j = i j-1 * i = power(i, j-1)*i } 2. Write a recursive method void sumReverse(int n) that when given an integer n > 0, prints the integer expression (with addition operator). For example, if n is 4, your method would print : 4 + 3 + 2 + 1 (After finishing this, try to write a method that prints 1 + 2 + 3 + 4 at home) public void sumReverse(int n) { if (n == 1) System.out.println(n); else { System.out.print(n + " + "); sumReverse(n-1); //print (n-1) + (n-2) + … + 2 + 1 } } 3. Write a recursive method String reverse(String s) which returns the reverse of a string. public String reverseR(String s) { if (s.length() < 2) return s;
Background image of page 1

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

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: else return s.charAt(s.length() - 1) + reverseR(s.substring(0,s.length() - 1)); } 4. Write a recursive method double findMax(double elements, int startIndex, int endIndex) that when given an array of doubles and an index of the array, it finds the largest element in the list. public double findMax(double elements, int startIndex, int endIndex){ if (startIndex == endIndex) return elements[startIndex]; else { double previousMax = findMax(elements, startIndex, endIndex-1); if (previousMax < elements[endIndex]) return elements[endIndex]; else return previousMax; } } Another way: public double findMax(double elements, int startIndex, int endIndex){ if (startIndex == endIndex) return elements[startIndex]; else { int midIndex = (startIndex + endIndex)/2; double max1 = findMax(elements, startIndex, midIndex); double max2 = findMax(elements, midIndex+1, endIndex); if (max1 < max2) return max2; else return max1; } }...
View Full Document

This note was uploaded on 11/09/2010 for the course CSE 71682 taught by Professor Nakamura during the Spring '10 term at ASU.

Page1 / 2

recExerciseSolnFall10 - else return s.charAt(s.length() -...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online