Read chapter 13 of Big Java 6th Edition and provide short an

Read chapter 13 of Big Java 6^th Edition and provide short answers to the following questions. Submit your answers in a text document (plain text or Microsoft Word format, please). 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.] 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.

Solution

Code1:

class Main{
  
public static void main(String[] args) {
  
       System.out.println(\"Frequency is: \" + count(\"Goodbye\", \'o\'));
  
}

public static int count(String c, char p) {
if (c.length() == 0) {
return 0;
} else if (c.charAt(0) == p) {

return 1 + count(c.substring(1, c.length()), p);
} else
return count(c.substring(1, c.length()), p);
}
}

Output:

Frequency is: 2

Code2:

import java.util.Scanner;
class Main{
int sum = 0, j = 0;
public static void main(String[] args){
int n;
Scanner s = new Scanner(System.in);
System.out.print(\"Enter the no. of elements you want:\");
n = s.nextInt();
int a[] = new int[n];
System.out.print(\"Enter all the elements you want:\");
for(int i = 0; i < n; i++){
a[i] = s.nextInt();
}
  
int x = add(a, a.length, 0);
System.out.println(\"Sum:\"+x);
}
  
public static int add(int a[], int n, int i){
if(i < n) {
return a[i] + add(a, n, ++i);
}   
else{
return 0;
}
}
}

Output:

 Read chapter 13 of Big Java 6^th Edition and provide short answers to the following questions. Submit your answers in a text document (plain text or Microsoft
 Read chapter 13 of Big Java 6^th Edition and provide short answers to the following questions. Submit your answers in a text document (plain text or Microsoft

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site