Question: I have this hw problem: Using recursion, create a program that will allow for a user to enter 5 numbers. The program will provide the
I have this hw problem: Using recursion, create a program that will allow for a user to enter 5 numbers. The program will provide the sum of all 5 numbers using recursive methods. I put together the following code. Please let me know what changes I should make and why: * PLEASE NOTE, I WANT TO KEEP THE CODE RELATIVELY THE SAME (HOW I SOLVE THE PROBLEM) AND IF THERE ARE ANY CHANGES MADE, I WOULD LIKE TO KNOW WHY THOSE CHANGES ARE BEST*
import java.util.Scanner;
public class NumberSum {
public static int sumOfNumbers(int number) {
if (number == 0) {return 0};
else {return (number % 10 + (sumOfNumbers(number/10)));
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print(Enter a five-digit number: );
int num = scnr.nextInt();
int sum = sumOfNumbers(num);
System.out.println(Sum of the numbers entered is + sum);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
