In: Computer Science
Program – version 1: Sum of Range Algorithm
Write a program that will sum the integers between a given range (limit your range from 0 to 50). For example, if the user want to add the integers between (and including) 1 and 10, then the program should add:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
Algorithm:
Test data (Use this data to test to ensure your program does the math correctly.):
Required program in java -->
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum=0; // declare variable sum and initialize it
with 0
System.out.println("Start Value: "); // ask user for start
value
int start = scanner.nextInt(); // read input from user and store
the value in start
System.out.println("End Value: "); // ask user for end value
int end = scanner.nextInt(); // read input from user and store the
value in end
if(start<end && start>=0 && start<=50
&& end>=0 && end<=50){ // if all the
conditions satisfies
for(int i=start; i<=end; i++){ // for loop executes from i=
start to i=end
sum=sum+i; // value of i is added in sum
}
System.out.println("Sum : "+sum); //print "Sum : " (value of
sum)
}
}
}