Intro to JAVA Problem 1: Summing It Up
Write a program, which takes two distinct integers separated by
space as input and prints the
sum of all the integers between them, including the two given
numbers. Note that the numbers
can appear in either order. You may assume that both numbers are
between
–10, 000 and 10, 000.
For example, if the input is as follows:
10 4
the output should be 49, since 10+9+8+7+6+5+4=49.
Similarly, if the input is
-3 10
the output should be 49,
since (-3) + (-2) + (-1) + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +
10 = 49
Input
The input will begin with a single line containing T , the number
of test cases to follow. The
remaining lines contain the lines to be calculated. Each of these
lines has two integers
separated by a single space.
Output
The output should consist of the sum of all numbers between the two
input numbers.
Sample Input Sample output
2
1 10 1+2+3+4+5+6+7+8+9+10 total 55
2 6 2+3+4+5+6 total 20
import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int testCases,num1,num2,sum,temp; testCases = scanner.nextInt(); while(testCases>0){ num1 = scanner.nextInt(); num2 = scanner.nextInt(); if(num2<num1){ temp = num1; num1 = num2; num2 = temp; } sum = 0; for(int i = num1;i<=num2;i++){ sum += i; } System.out.println(sum); testCases--; } } }
Get Answers For Free
Most questions answered within 1 hours.