Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Informix Database Administrators Survival Guide

Authors: Joe Lumbley

1st Edition

0131243144, 978-0131243149

More Books

Students also viewed these Databases questions