I’m trying to practice understanding recursion in java and this code keeps giving me an unexpected output. I want to subtract all numbers between a user submitted range.
For example, if the user inputs 1 and 3 it should output -4 (1-2-3=-4) however i keep getting a different result.
import java.util.Scanner;
public class recursionTest {
public static void main(String[] args)
{
int input1;
int input2;
System.out.println("Please input lower value: ");
Scanner inputOneTaker = new Scanner(System.in);
input1 = inputOneTaker.nextInt();
System.out.println("Please input higher value: ");
Scanner inputTwoTaker = new Scanner(System.in);
input2 = inputTwoTaker.nextInt();
int result = sum(input1,input2);
System.out.println(result);
}
public static int sum ( int x, int y)
{
if (x < y) {
return x - sum(x+1,y);
}
else {
return y;
}
}
}
For example, if the user inputs 1 and 3 it should output -4 (1-2-3=-4) however i keep getting a different result.
Christopher Marcano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.