The sum of the first n positive integers is and can easily b

The sum of the first n positive integers is:

and can easily be computed using a for-loop:

public int sumToN(int n) {

  int sum = 0;

for (int i = 1; i <= n; i++) {

sum += i;

  }

return sum;

}

It is also possible to recursively compute the sum by recognizing that sum(n) = n + sum(n - 1). Write a recursive version of sumToN(...).

Solution

Below is a recursive version of sumToN() method()

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

The sum of the first n positive integers is: and can easily be computed using a for-loop: public int sumToN(int n) { int sum = 0; for (int i = 1; i <= n; i++

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site