Complete the code to return the sum of elements in the array recursively.
public int sumArray(int[] arr, int index) {
if (index == [1]) {
return 0;
}
return arr[index] + sumArray(arr, index + 1);
}The base case is when index reaches the length of the array, meaning no more elements to add.
Complete the code to check if a string is a palindrome using recursion.
public boolean isPalindrome(String s, int start, int end) {
if (start >= end) {
return true;
}
if (s.charAt(start) != s.charAt([1])) {
return false;
}
return isPalindrome(s, start + 1, end - 1);
}We compare characters at start and end indices to check palindrome.
Fix the error in the recursive function to find the maximum element in an array.
public int findMax(int[] arr, int index) {
if (index == arr.length - 1) {
return arr[index];
}
int maxInRest = findMax(arr, [1]);
return Math.max(arr[index], maxInRest);
}The recursive call should move forward by increasing the index by 1.
Fill both blanks to create a recursive function that counts occurrences of a character in a string.
public int countChar(String s, char c, int index) {
if (index == [1]) {
return 0;
}
int count = (s.charAt(index) == [2]) ? 1 : 0;
return count + countChar(s, c, index + 1);
}The base case stops when index reaches string length. We compare character at index with c.
Fill all three blanks to create a recursive function that builds a reversed string.
public String reverseString(String s, int index) {
if (index == [1]) {
return "";
}
return reverseString(s, index + 1) + s.[2]([3]);
}The base case stops when index reaches string length. We get character at current index and append it after recursive call.
