Post

Created by @nathanedwards
 at November 1st 2023, 9:36:17 pm.

Exam Question:

Consider the following recursive method:

public static int recursiveSum(int n) {
    if (n == 0) {
        return 0;
    }
    return n + recursiveSum(n - 1);
}

Assume we call the recursiveSum method with the argument 5. What will be the output of the method? Show the step-by-step process.

Answer:

The output of the method will be 15.

Step-by-step explanation:

  1. We call the recursiveSum method with the argument 5.
  2. The method checks if n is equal to 0. Since n is 5, this condition is false.
  3. The method returns 5 + recursiveSum(5 - 1).
  4. We now need to calculate recursiveSum(5 - 1).
  5. Again, the method checks if n is equal to 0. Since n is now 4, this condition is false.
  6. The method returns 4 + recursiveSum(4 - 1).
  7. We now need to calculate recursiveSum(4 - 1).
  8. The method checks if n is equal to 0. Since n is now 3, this condition is false.
  9. The method returns 3 + recursiveSum(3 - 1).
  10. We now need to calculate recursiveSum(3 - 1).
  11. The method checks if n is equal to 0. Since n is now 2, this condition is false.
  12. The method returns 2 + recursiveSum(2 - 1).
  13. We now need to calculate recursiveSum(2 - 1).
  14. The method checks if n is equal to 0. Since n is now 1, this condition is false.
  15. The method returns 1 + recursiveSum(1 - 1).
  16. We now need to calculate recursiveSum(1 - 1).
  17. The method checks if n is equal to 0. Since n is now 0, this condition is true.
  18. The method returns 0.
  19. Going back to the previous recursive calls, we substitute the returned values:
    • recursiveSum(1 - 1) returns 0, so the result is 1 + 0 = 1.
    • recursiveSum(2 - 1) returns 1, so the result is 2 + 1 = 3.
    • recursiveSum(3 - 1) returns 3, so the result is 3 + 3 = 6.
    • recursiveSum(4 - 1) returns 6, so the result is 4 + 6 = 10.
    • recursiveSum(5 - 1) returns 10, so the final result is 5 + 10 = 15.
  20. Thus, the output of the method with the argument 5 will be 15.