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

Time:02-19

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            
  • Related