In: Computer Science
(java)Write a recursive method public static int
sumForEachOther(Int n) that takes a positive Int as an argument and
returns the sum for every other Int from n down to 1. For example,
sumForEachOther(8) should return 20, since 8+6+4+ 2=20.And the call
sumForEachOther(9) should return 25 since 9+7+5 + 3+1-=25.
Your method must use recursion.
Explanation:I have implemented the method sumForEachOther() recursively, I have also provided a main method in a RecursiveSum class to show the output of the program, please find the image attached with the answer.Please upvote if you liked my answer and comment if you need any modification or explanation.
//method
public static int sumForEachOther(int n) {
if (n < 1) {
return 0;
}
return n + sumForEachOther(n -
2);
}
//demo code
public class RecursiveSum {
public static int sumForEachOther(int n) {
if (n < 1) {
return 0;
}
return n + sumForEachOther(n -
2);
}
public static void main(String[] args) {
int sum = sumForEachOther(8);
System.out.println(sum);
sum = sumForEachOther(9);
System.out.println(sum);
}
}
Output: