Write a recursive method public static int sumEveryOther(int n) that takes a positive int as an argument and returns the sum of every other int from n down to 1.
For example, the call sumEveryOther(10) should return 30, since 10 + 8 + 6 + 4 + 2 = 30.
The call sumEveryOther(9) should return 25 since 9 + 7 + 5 + 3 + 1 = 25.
Your method must use recursion.
public static int sumEveryOther(int n) { if (n > 0) { return n + sumEveryOther(n - 2); } return 0; }
public class SumEveryOther { public static int sumEveryOther(int n) { if (n > 0) { return n + sumEveryOther(n - 2); } return 0; } public static void main(String[] args) { System.out.println(sumEveryOther(10)); System.out.println(sumEveryOther(9)); } }
Get Answers For Free
Most questions answered within 1 hours.