Define a recursive rangeSum(from, to) method that calculates and prints the sum of numbers between the two values inclusive. IN JAVA.
OUTPUT
rangeSum(1,5) -> 15
rangeSum(1,5) -> 1+2+3+4+5=15
rangeSum(-3,4) -> 4
rangeSum(-3,4) -> -3+-2+-1+0+1+2+3+4=4
rangeSum(-5, 7) -> 13
rangeSum(-5, 7) -> -5+-4+-3+-2+-1+0+1+2+3=-9
please write main method as well as output for three above methods.
public class RangeSumTest { public static int rangeSum(int from, int to) { if (from > to) return 0; System.out.print(from); if (from != to) { System.out.print("+"); } else { System.out.print("="); } return from + rangeSum(from + 1, to); } public static void main(String[] args) { System.out.println(rangeSum(1, 5)); System.out.println(rangeSum(-3, 4)); System.out.println(rangeSum(-5, 7)); } }
Get Answers For Free
Most questions answered within 1 hours.