Chapter 16. PC #8. Sum of Numbers (page 1073) Write a (Java) method that accepts
ID: 3845966 • Letter: C
Question
Chapter 16. PC #8. Sum of Numbers (page 1073)
Write a (Java) method that accepts an integer argument and returns the sum of all the integers from 1 up to the number passed as an argument. For example, if 50 is passed as an argument, the method will return the sum of 1, 2, 3, 4, . . . 50. Use recursion to calculate the sum. Demonstrate the method in a program.
The program should ask the user to enter a number, which is then used to display the sum. if the user enters -1, then exit the program.
Test Case 1
Test Case 2
Standard Input5ENTER 10ENTER -1ENTER
Explanation / Answer
import java.util.*;
public class Sum{
static int calculateSum(int num)
{
int sum;
if(num == 1)
return 1;
else
{ sum = num + calculateSum(num-1);
return sum;
}
}
public static void main(String []args){
System.out.println("Please enter a number");
int num,sum;
Scanner s = new Scanner(System.in);
num = s.nextInt();
if(num == -1)
{
System.exit(0);
}
else
{
sum = calculateSum(10);
System.out.println("Sum of first "+ num + " number is " + sum);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.