The following program is intended to accept the input of an integer in from the
ID: 3596409 • Letter: T
Question
The following program is intended to accept the input of an integer in from the keyboard and then recursively compute the sum of the integers from in down to and including 1. You may assume that in >= 1. Strictly speaking the program with produce the correct result, but it is not correct. What change will make it work as described in the specification?
public class RecursiveSum public static void main(String[] args) int sumStart = 0; int highstart = 0; String inputString Scanner keyboard new Scanner(System.in); System.out.println("Enter high start for recursive addition..."); inputString keyboard.nextLine(); highStart Integer.parselnt(inputString); System.out.println ("The sum of integers from 1 to "+ highStart+"-"recursiveAdd (highStart)); public static int recursiveAdd (int addParm) if (addParm =:0) return addParm; return addParm recursiveAdd(addParm - 1);Explanation / Answer
RecursiveSum.java
import java.util.Scanner;
public class RecursiveSum {
public static void main(String[] args) {
int sumStart =0;
int highStart = 0;
String inputString = "";
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter high start for recursive addition: ");
inputString = keyboard.nextLine();
highStart = Integer.parseInt(inputString);
System.out.println("The sum of integers from 1 to "+highStart+" = "+recursiveAdd(sumStart, highStart));
}
public static int recursiveAdd(int sumStart, int highStart) {
if(sumStart == highStart)
return sumStart;
return sumStart+recursiveAdd(sumStart+1, highStart);
}
}
Output:
Enter high start for recursive addition:
10
The sum of integers from 1 to 10 = 55
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.