This code below allows the user to input values and then takes the sum of all values given and then gives the sum by recursion. The code below allows the user to input each int and provides sum
import java.util.Scanner;
public class Recursion {
public static int Recursion1(int userSum)
{
if (userSum == 0) {
return userSum;
} else {
return userSum + Recursion1(userSum - 1);
}
}
public static void main(String[] args)
{
int userSum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Program Started");
System.out.println(Recursion1(userSum));
int counter = 0;
int i;
for(i=0;i < 5;i++) {
//ask user input
System.out.print("Enter any number: ");
userSum = scan.nextInt();
}
scan.close();
int sumNum=Recursion1(userSum);
System.out.println("The sum of digits is: "+sumNum);
System.out.println("Scanner Closed.");
}
}
8+7+6+5+4+3+2+1. That is why doing1,2,3,4,5seems like it is working, since the last one is5it does5+4+3+2+1Recursion1should berecursion1according to java naming conventions.