Show the Java code for a recursive method int count; (String text, char ch) that
ID: 3939711 • Letter: S
Question
Show the Java code for a recursive method int count; (String text, char ch) that returns the number of times the character ch appears. For example, count ("Goodbye", ' o') would return 2. You will need to do this recursively by getting a character (first or last) from the string, recursively calling the count () method on the String without the chosen character, and (if the chosen character is equal to ch), add one to the result of the count() on the shorter string. [No points will be given for a solution that uses a loop.] b. Show the java code for a method public static int arraySum(int[] a) that uses recursion to compute the sum of all values in an integer array.)Explanation / Answer
Hi, Please find my working implementation.
Please let me know in case of any issue.
public int count(String text, char c){
// if text is null
if(text == null)
return 0;
// if test has only one character
if(text.length() == 1){
if(text.charAt(0) == c)
return 1;
else
return 0;
}
// if current character is equal to c then add 1 and call for remaining character
if(text.charAt(0) == c)
return (1 + count(text.substring(1), c));
else
return count(text.substring(1), c);
}
public static int arraySum(int[] a){
// base case
if(a == null)
return 0;
// if array has only one element
if(a.length == 1)
return a[0];
return a[0] + arraySum(Arrays.copyOfRange(a, 1, a.length));
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.