Part #1 Write a recursive method that takes a word as input and displays that wo
ID: 3725610 • Letter: P
Question
Part #1
Write a recursive method that takes a word as input and displays that word with all characters separated by a space. It should have this signature:
Public static void addSpaces(String strWord)
For example, addSpaces(“hello”) displays “h e l l o”. Use the main() method to ask the user to enter a word and then call addSpaces().
Part #2
Write a recursive method that calculates the sum of integers in an array. The signature should be:
Public static int sumArray(int[] iArray)
For example, sumArray({1,2,3,4}) returns 10. Make up a small array and then pass it into the method from main() to test it.
Hint: You could use System.arraycopy() to copy the array to a new smaller array each time.
Note
Take note of the return types. Part 1 returns void so there’s no return statement. Start building the output in the addSpaces() method (before the recursive call). Part 2 returns “int” so the return statement will look something like the Factorial example.
Explanation / Answer
public class test3 {
public static void addSpaces(String strWord)
{//
// a recursive method that takes a word as input and displays that word with all characters separated by a space
int i=strWord.length();
if(strWord.length()>1)
addSpaces(strWord.substring(0, strWord.length()-1));
System.out.print(strWord.charAt(i-1));
System.out.print(" ");
}
public static int sumArray(int[] iArray,int n)
{
int sum=0;
//a recursive method that calculates the sum of integers in an array.
if(n>1)
sum = sumArray(iArray,n-1);
return sum+iArray[n-1];
}
public static int sumArray(int[] iArray)
{
int sum = sumArray(iArray,iArray.length);
return sum;
}
//testing//
public static void main(String argv[])
{
addSpaces("hello");
System.out.println();
int a[]= {1,2,3,4};
int n =sumArray(a);
System.out.println(n);
}
}
output:
run:
h e l l o
10
BUILD SUCCESSFUL (total time: 1 second)