# 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.

Question
115 views

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.

check_circle

Step 1

Following is the loop which prints the sum of all even and odd integers entered by the user and will terminate if the negative integer is entered.

while (n >= 0) {

// checks if number entered is even or not

if (n % 2 == 0)

even += n;//store all even numbers

else

odd += n;//store all odd numbers

//promt user to enter positive number

cout << "Enter a positive number. ";

cin >> n;

}

Step 2

C++ program for above scenario is given below:

The program uses three variables n, even, odd to store the number entered by user, sum of all even number and sum of all odd numbers respectively. While loop will execute only if the number entered by the user is positive, if a negative number is entered loop will terminate and will print the sum of all even and odd integers.

Step 3

Program code:

#include <iostream> //header file for input output

using namespace std;

int main() {

// declaring variables

int even = 0, odd = 0, n;

//promt user to enter positive number

cout << "Enter a positive number. ";

cin >> n;

// loop to check that number entered is non-negative.

while (n >= 0)

{

// checks if number entered is even or not

if (n % 2 == 0)

even += n;//store all even integers

else

...

### Want to see the full answer?

See Solution

#### Want to see this answer and more?

Solutions are written by subject experts who are available 24/7. Questions are typically answered within 1 hour.*

See Solution
*Response times may vary by subject and question.
Tagged in