Java Program: (name this Lab 14_Problem4) Write a main() and recursive method na
ID: 3770236 • Letter: J
Question
Java Program: (name this Lab 14_Problem4)
Write a main() and recursive method named fiSumDigits() that calculates the sum of the digits. The sum of the digits is the sum of every number that leads up to the value, beginning with 1. For 6, it would be 1 + 2 + 3 + 4 + 5 + 6, or working backwards, 6 + 5 + 4 + 3 + 2 + 1. Both yield 21.
In main(), simply call the value-returning method and pass it an integer value of 6, hard coded in the method call.
Have the recursive method receive the parameter, then calculate and return the sum of the digits.
Explanation / Answer
class recur_sum
{
public static int fiSumDigits(int n)
{
// Basic Case to stop the recursion
if (n== 0)
{
return sum;
}
else
{
sum = sum + n;
n--;
return fiSumDigits(sum);
}
}
public static void main(String[] args)
{
int sum = fiSumDigits(6);
System.out.println("Sum of the digits from 1 to 6 is "+sum);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.