CS 256 - Recursion Problems

  1. Write a recursive function reverse(str) to reverse a string.
    String reverse(String str) {                
      if (str.length() <= 1)
         return str;
      else
         return reverse(str.substring(1)) + str.charAt(0);
    }
    
  2. Write a recursive function contains(str,ch) that returns true if the string str contains the character ch. Return false otherwise.
      
    boolean contains(String str, char ch) {
      // base case, the empty string does not contain ch
      if (str.length() == 0)
         return false;
            
      // check if the first character is ch
      else if (str.charAt(0) == ch)
         return true;
            
      // otherwise look in the rest of the string, recursively
      else
         return contains(str.substring(1), ch);
    }
    
  3. Write a recursive function to sum the number of digits in an integer. For example, sum(7128) should return 18.
    int sum_digits(int x) {
      if  (x == 0) 
        return 0;
      else
        return (x % 10) + sum_digits(x/10);
    }
    
  4. Self check 1,6 on page 251.
  5. Self check 1 page 259.
  6. Self check 1,2 page 267.

For answers to the self check exercises see the solutions manual in the QRC.