Write a program named: SumRange.java
This program will prompt the user for two integer values, a min and a max. Then, calculate the sum of all integers from min to max, including both. Do NOT assume that the first value entered will be smaller than the second. Make sure you check which is the smallest and largest.
Then print the result to the screen.
Here are several sample I/O-s (user input in orange bold italics):
Enter two integers, and I'll tell you the sum of all integers between the two (including both): 5 12
The sum is: 68
Enter two integers, and I'll tell you the sum of all integers between the two (including both): 10 2
The sum is: 54
Enter two integers, and I'll tell you the sum of all integers between the two (including both): -5 -10
The sum is: -45
Enter two integers, and I'll tell you the sum of all integers between the two (including both): -5 5
The sum is: 0
import java.util.Scanner;
public class SumRange {
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
System.out.print("Enter two integers, and I'll tell you the sum of all integers between the two (including both): ");
int min = keyBoard.nextInt();
int max = keyBoard.nextInt();
int sum = 0;
if(min>max) {
int temp=max;
max=min;
min=temp;
}
for (int i = min; i <= max; i++) {
sum += i;
}
System.out.println(sum);
keyBoard.close();
}
}
Comments
Leave a comment