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
//SummingItUp.java import java.util.Scanner; public class SummingItUp { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t,n1,n2,sum,tmp; t = scanner.nextInt(); while(t>0){ n1 = scanner.nextInt(); n2 = scanner.nextInt(); if(n2<n1){ tmp = n1; n1 = n2; n2 = tmp; } sum = 0; for(int i = n1;i<=n2;i++){ sum += i; } System.out.println(sum); t--; } } }
Get Answers For Free
Most questions answered within 1 hours.