Method 1:
package com.smbea.demo; public class Student { private int sum = 0; /** * Recursive sum* @param num */ public void sum(int num) { this.sum += num--; if(0 < num){ sum(num); } else { System.out.println("sum = " + sum); } } }Method 2:
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 is not recursive! I won't discuss it here.
The above two simple methods of recursive summation in Java (recommended) are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.