Answer to Question #242716 in Java | JSP | JSF for java2

Question #242716

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


1
Expert's answer
2021-09-27T01:16:53-0400


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();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS