In this example is demonstrated you the sum of N natural numbers using recursion technic
Java Code: Write a program to calculate the sum of n natural numbers by using recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public static int sum(int number) { if(number > 0) { return number + sum(number-1); } return number; } public static void main(String[] args) { System.out.println("Sum= " + sum(5)); } |
Output: