Search code examples
javarecursionstaticstatic-methodscumulative-sum

How can I use an instance variable with a static recursive method in java? (cumulative sum problem)


I'm writing some code to figure out the cumulative sum between two numbers recursively, but the method i wrote requires updating a would-be instance variable called "ans".

Since the problem I'm looking at requires the method header to be "public static int sumBetween(int a, int b)", I'm having issues using a non-static variable for this method.

Currently, I have the variable ans set to static but this can of course only run once, and if I call the method afterwards it starts with the variable ans being the last answer, not 0.

I'm new to recursion so I though I would start with some of these problems. Thank you!

Code:

/* EXERCISE 2: Cumulative sum
 * 
 * public static int sumBetween(int a, int b)
 * The goal is to find the sum of the values from 𝑎 to 𝑏. In math, we would write this problem as ∑𝑏𝑖=𝑎𝑖
 */
 static int ans =0;
 
 public static int sumBetween(int a, int b) {
     // base case
     if (a==b) {
         ans = ans +b;
         return ans;
     }
     // recursion
     ans = ans + a + b;
     return sumBetween(a+1, b-1);
 }

Solution

  • Someone answer a second ago but deleted their answer - regardless, thank you stranger because it worked:

     public static int sumBetween(int a, int b) {
         return sumBetweenHelper(a, b, 0);
     }
     
     public static int sumBetweenHelper(int a, int b, int ans) {
         // base case
         if (a==b) {
             ans = ans +b;
             return ans;
         }
         // recursion
         ans = ans + a + b;
         return sumBetweenHelper(a+1, b-1, ans);
     }