Recursion Practice Problems

1. Write a recursive method called sumDigits to return the sum of all of the digits in a given integer value.  Use a helper method if necessary.

Example tests:

assertEquals(0, sumDigits(0));
assertEquals(8, sumDigits(1331)); // 1 + 3 + 3 + 1 = 8
assertEquals(16, sumDigits(14641)); // 1 + 4 = 6 + 4 + 1 = 16

2. Write a tail recursive version of the above method.

3. Write a recursive method called countVowels that returns the number of vowels in a given String.  (You can assume that the letter "y" is not a vowel.)  Use a helper method if necessary.

Example tests:

assertEquals(0, countVowels(""));
assertEquals(9, countVowels("Four score and seven years"));
assertEquals(5, countVowels("The quick brown fox"));
assertEquals(8, countVowels("One if by Land - Two if by Sea"));

4. Write a tail recursive version of the above method.

5. Write a recursive method called reverseArray that reverses the elements of a given array of int values.  Use a helper method if necessary.

Example test:

int[] arr = new int[]{ 8, 26, 25, 20, 36, 24, 43, 13 };

reverseArray(arr);

assertEquals(13, arr[0]);
assertEquals(43, arr[1]);
assertEquals(24, arr[2]);
assertEquals(36, arr[3]);
assertEquals(20, arr[4]);
assertEquals(25, arr[5]);
assertEquals(26, arr[6]);
assertEquals(8, arr[7]);