Write a Java program that uses while loops to read an integer number between 20
ID: 3674643 • Letter: W
Question
Write a Java program that uses while loops to read an integer number between 20 and 60, then the program prints out the entered value followed by (on a separate line) the sum of all even integer values between 2 and the entered number (including the entered value if even). Use a while loop to validate the user input before determining and printing the sum. In addition, design your program such it allows the user to re-run the program with a different input. Use proper labels for the outputs as shown in the examples below.Explanation / Answer
//header files
import java.util.*;
public class HelloWorld{
public static void main(String[] args) {
// declre variables
int sum = 0;
int count = 2;
//getting input from user
Scanner input = new Scanner(System.in);
System.out.println("Entered value :");
int endNum = input.nextInt();
// error message when value is less tahn 1
if (endNum < 2) {
System.out.println("Input value must not be less than 2");
return ;
}
// sum of values
while (count <= endNum) {
sum = sum + count;
count += 2;
}
// display output
System.out.println("Sum of even numbers between 2 and " + endNum + " is: " + sum);
}
}
sample output
Entered value :
20
Sum of even numbers between 2 and 20 is: 110
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.