Question: Java 3) Use recursion to add all of the numbers between 5 to 10. public class Recursion2 { public static void main(String[] args) { int

Java

3) Use recursion to add all of the numbers between 5 to 10.

public class Recursion2 { public static void main(String[] args) { int result = sum(5, 10); System.out.println(result); } public static int sum(int start, int end) { if (end > start) { return end + sum(start, end - 1); } else { return end; } } }

4) Use recursion to add all of the numbers up to 10.

  • When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the result. When k becomes 0, the function just returns 0. When running, the program follows these steps:
  • 10 + sum(9) 10 + ( 9 + sum(8) ) 10 + ( 9 + ( 8 + sum(7) ) ) ... 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0) 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
public class Recursion1 { public static void main(String[] args) { int res = sum(10); System.out.println(res); } public static int sum(int k) { if (k > 0) { return k + sum(k - 1); } else { return 0; } } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!