Using your knowledge on repetition structures (while, do, and for loops), create
ID: 440166 • Letter: U
Question
Using your knowledge on repetition structures (while, do, and for loops), create a small Java program that uses all of these concepts. To begin, write a program that reads in numbers from the user until they enter a -1 value; this program should sum all the values only if the value is even (i.e., if the user enters an odd number, ignore it). Then, modify this program to read the input from a file instead of the user.
Requirements:
A) Use a repetition structure (while, do, or for) as appropriate
B) Read in values from the user until the user types -1
C) If the value entered each time through the loop is even, add it to the sum
D) Display the sum outside of the loop, whenever the user types -1 (be sure not to include the -1 in the sum)
Hint: realize that if a number is even, then the integer remainder when it is divided by 2 will equal 0, so if the value is n, then n % 2 will equal 0.
Explanation / Answer
//reads from user //SumEven.java import java.util.Scanner; public class SumEven { public static void main(String[] args) { Scanner input=new Scanner(System.in); int sum=0; int num; System.out.println("Enter integers to sum even values (-1 to exit): "); //while(input.hasNextInt() && num!=-1); do{ num=input.nextInt(); if(num%2==0) sum+=num; }while(num!=-1); System.out.println("The sum of the even numbers is "+ sum); input.close(); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.