Basic java recursion 1) comments at the beginning of your program that state you
ID: 3752213 • Letter: B
Question
Basic java recursion
1) comments at the beginning of your program that state your name, the lab assignment number, the text editor or IDE you used, the Java version you used, and the operating system you used
(2) comments that explain essential regions of programming logic used in your source code
(3) comments that explain the general purpose of all classes and methods used in your source code
(4) comments that explain the essential variables used in your source code
LAB 1c: Recursive Sum [ recursiveSum.java ] 25 points.
Write a method called recursiveSum() that takes two non-negative integer parameters and recursively calculates their sum. You only need to write the method to calculate the sum of two integer values that are both greater than or equal to 0. recursiveSum() should be included inside a class you name RSum and should have a public static void main() method. The main() method should be used to pass the value of the parameter needed to recursiveSum(), and should end after the recursiveSum() once method has completed. Use hardcoded values for a single integer value used in main() that is passed as the parameter to recursiveSum().
Hint: In a way similar to taking the recursive formula for factorial:
0! = 1
1! = 1
n! = n * (n - 1)
and solving some small values of it such as:
factorial(0) = 0
factorial(1) = 1
factorial(3) = 3 * factorial(2) = 3 * 2! = 6
factorial(4) = 4 * factorial(3) = 4 * 6 = 24
factorial(5) = 5 * factorial(4) = 5 * 24 = 120
factorial(n) = n * factorial(n-1)
then writing the following method name, data type, and input parameter as the Java code:
public static int factorial(int n) {
// factorial code goes here
.
.
.
}
Determine what the sum would be for 0 + 0, 0 + 1, 1 + 0, and 1 + 1, then return the sum of each one of those as the most basic answer of the recursion. The recursive logic should follow a pattern much like this for the small values 4 and 2:
4 + 2 =
(3 + 1) + 2 =
((2 + 1) + 1) + 2 =
(((1 + 1) + 1) + 1) + 2 =
((2) + 1) + 1) + 2 =
((3) + 1) + 2 =
(4) + 2 =
6
Notice only one of the two numbers is recursively reduced to 1 + 1 and then has + 1 added to the recursive return value.
Explanation / Answer
public class RSum {
public static void main(String[] args) {
// TODO Auto-generated method stub
double result=recursiveSum(10,2);
System.out.println(result);
}
public static int factorial(int numberinput) {
if (numberinput == 0)
return 1;
else
return (factorial(numberinput-1));
}
public static double recursiveSum(int firstnumber, int secondnumber) {
if (firstnumber == 0)
return secondnumber;
else
return factorial(firstnumber) + recursiveSum(firstnumber-1,secondnumber);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.