Answer to Question #253675 in Java | JSP | JSF for lee

Question #253675

Using a for loop create a program that will prompts the user for two numbers and then print out a summation list of all the between the two given numbers, starting from the small number to the big number. For negative numbers use brackets when printing the summation

Sample Run1

Enter two numbers: 1 10

Output1: Sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Sample Run2

Enter two numbers: -3 3

Output2: Sum = (-3) + (-2) + (-1) + 0 + 1 + 2 + 3 = 0

1
Expert's answer
2021-10-20T14:29:33-0400
import java.util.Scanner;
public class App {
	/**
	 * The start point of the program
	 * 
	 * @param args
	 */
	public static void main(String[] args) {


		Scanner keyBoard = new Scanner(System.in);
		System.out.print("Enter two numbers: ");
		int n1 = keyBoard.nextInt();
		int n2 = keyBoard.nextInt();
		int sum=0;
		System.out.print("Sum = ");
		for(int i=n1;i<n2;i++) {
			sum+=i;
			if(i>=0) {
				System.out.print(i+" + ");
			}else {
				System.out.print("("+i+") + ");
			}
		}
		sum+=n2;
		if(n2>=0) {
			System.out.print(n2);
		}else {
			System.out.print("("+n2+")");
		}
		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