English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Two Simple Methods for Recursive Summation in Java (Recommended)

Method one:

package com.smbea.demo; 
public class Student { 
  private int sum = 0; 
  /** 
   * Recursive Summation 
   * @param num 
   */
  public void sum(int num) { 
    this.sum += num--; 
    if(0 < num){ 
      sum(num); 
    } else { 
      System.out.println("sum = ", + sum); 
    } 
  } 
}

Method two:

package com.smbea.demo; 
public class Test { 
  public static void main(String[] args) { 
    Teacher teacher = new Teacher(); 
    teacher.sum(); 
  } 
  public static int sum(int num){ 
    if(1 == num){ 
      return 1; 
    } else { 
      return num + sum(num - 1); 
    } 
  }; 
}

Of course, there are other methods, such as using for loops, while loops, etc., which do not belong to recursion! This will not be discussed here.

This article on the two simple methods of recursive summation in Java (recommended) is all the content that the editor shares with everyone. Hope it can give everyone a reference, and I also hope everyone will support the Yell Tutorial more.

You May Also Like