JohannesF
JohannesF

Reputation: 1

Turning a iteration into a recursion

Good day!

I just wrote a code as an iteration which is supposed to sum up even numbers in between 0 and y.

I've been sitting now on my desk for about two hours thinking on how to write the same code in a recursion - without any progress so far. The only explanations I find on the internet explain it for one simple repeat of one specific change - unlike my code which includes two. ("result = result + x;" and "x = x + 2;" ) Could someone please explain to me how I turn this kind of iteration into a recursion? Thanks in advance!

 public class Sum {

   static int method(int y) { 
     int result = 0; 
     for (int x = 2; x<=y;)
     {
        result = result + x;   
        x = x + 2; 
     }
     return result;
   } 

   public static void main(String[ ] args) {
      int result = method(35); 
      System.out.println("Sum of even numbers between 0-35: " +result); 
   }
}

Upvotes: 0

Views: 52

Answers (1)

M. le Rutte
M. le Rutte

Reputation: 3563

The total of the numbers is the total of this number plus the total of the number minus 2. Written in code:

int method(int y) { 
  if (y <= 0) {
     return 0;
  } else {
     return y + method(y - 2);
  }
} 

Needless to say that recursion in this form is not necessary, and will create a StackoverflowException when y is a really large number. Some languages allow you to write a recursive function and indicate it is a tail recursion so that the compiler actually transforms it to an iteration.

Upvotes: 2

Related Questions