Java - Use recursive function to sum numbers

Description

Use recursive function to sum numbers

Demo

public class Main {

  public static int Summation(int n) {
    // Base Case: WE ARE AT THE END
    if (n <= 0) {
      return 0; // additive identity property
    }/*from w w  w  .j a v  a2  s .c om*/
    // Recursive Case: KEEP GOING
    else {
      // 3 + Summation(2)
      // 3 + 2 + Summation(1)
      // 3 + 2 + 1 + Summation(0)
      // 3 + 2 + 1 + 0 = 6
      return n + Summation(n - 1);
    }
  }

  public static void main(String args[]) throws Exception {

    System.out.println(Summation(3));

  }
}

Related Topic