So I've seen this question asked about for help before but I had a different question about it.
The question is: (Occurrences of a specified character in an array) Write a recursive method that finds the number of occurrences of a specified character in an array. You need to declare the following two methods. The second one is a recursive helper method.
public static int count(char[] chars, char ch)
public static int count(char[] chars, char ch, int high)
The following code works perfectly fine:
public class RecursiveCharacterOccurences {
public static int count(char[] chars, char ch) {
return count(chars, ch, chars.length - 1);
}
private static int count(char[] chars, char ch, int index) {
if (index == -1) {
return 0;
}
if (chars[index] == ch) {
return 1 + count(chars, ch, index - 1);
}
return count(chars, ch, index - 1);
}
public static void main(String[] args) {
char[] test = {'a', 'b', 'a', 'c', 'd', 'a', 'e', 'a', 'f', 'g', 'h', 'a', 'i', 'a'};
System.out.println(count(test, 'a'));
}
}
I was wondering if someone could explain why that is so much better than the following code, I had done this first before realizing it wasn't actually recursion but to me it seems like a lot less code.
public class RecursiveCharacterOccurences {
public static int count(char[] chars, char ch) {
return count(chars, ch, 0);
}
private static int count(char[] chars, char ch, int count) {
for (char a : chars) {
if (a == ch) {
count++;
}
}
return count;
}
public static void main(String[] args) {
char[] test = {'a', 'b', 'a', 'c', 'd', 'a', 'e', 'a', 'f', 'g', 'h', 'a', 'i', 'a'};
System.out.println(count(test, 'a'));
}
}
Thanks!