62.8k views
0 votes
Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out the sum of all the even integers read and the sum of all the odd integers read(The two sums are separated by a space). Declare any variables that are needed.

1 Answer

5 votes

Answer:

import java.util.Scanner;

public class num4 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

int sumOdds =0;

int sumEvens =0;

int num;

do{

System.out.println("Enter positive integers");

num = in.nextInt();

if(num%2==0){

sumEvens+=num;

}

else if (num%2!=0){

sumOdds+=num;

}

}while (num>0);

System.out.println("The sum of evens: "+sumEvens);

System.out.println("The sum of odds: "+sumOdds);

}

}

Step-by-step explanation:

  • Import Scanner class to prompt and receive user input
  • Declare the following variables and initialize them int sumOdds =0, int sumEvens =0, int num;
  • Create a do....while loop That continously prompts user to enter a positive number. The loop should terminate when a negative number is enters (n<=0)
  • Within the while loop use an if condition with the modulo (%) operator to determine even and odd numbers and add to the respective variables
  • Outside of the while loop Print sum of odds and sum of evens

User Darshit Shah
by
5.7k points