In: Computer Science
JAVA
5- Write a program that prompts the user to enter two (2) numbers and compute the sum of the numbers between these two numbers (including the numbers entered). If the user Enters 2 and 6. The program will calculate the sum of the numbers: 2+3+4+5+6 and will display the result.
Enter First number> 2
Enter second number> 6
The sum is 20
Using while loop
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int first,second,sum = 0,i;
Scanner input = new Scanner(System.in);
System.out.print("Enter First number ");
first = input.nextInt();
System.out.print("Enter second number ");
second = input.nextInt();
i = first;
while(i<=second){
sum = sum + i;
i++;
}
System.out.println("The sum is "+sum);
}
}
Screenshot of the program with output
Using for loop
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int first,second,sum = 0,i;
Scanner input = new Scanner(System.in);
System.out.print("Enter First
number ");
first = input.nextInt();
System.out.print("Enter second
number ");
second = input.nextInt();
for(i=first;i<=second;i++){
sum = sum + i;
}
System.out.println("The sum is
"+sum);
}
}
Screenshot of the program with output
NOTE: If you want to change something , please let me know through comments; I will surely revert back to you.
Please give a up vote .....
Thank you...