137k views
2 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.

User Alica
by
5.2k points

1 Answer

3 votes

Answer:

The loop for the given scenario is shown.

while( num >= 0 )

{

if( num%2 == 0 )

sum_even = sum_even + num;

else

sum_odd = sum_odd + num;

cout << "Enter a positive number." << endl;

cin >> num;

}

Step-by-step explanation:

The program uses three variables to hold the user input, sum of even numbers and sum of odd numbers.

int sum_even, sum_odd, num;

The sum variables are initialized.

sum_even = 0;

sum_odd = 0;

Only positive input from the user needs to be considered as per the question, hence, while loop is used.

This loop will execute only if the user inputs valid number. Upon entering the negative number which is less than 0, the loop terminates.

Following this, the sum of even numbers is displayed followed by the sum of negative numbers.

cout << sum_even << " " << sum_odd << endl;

The c++ program for the given problem statement is as follows.

#include <iostream>

using namespace std;

int main()

{

// variables declared for sum and input

int sum_even, sum_odd, num;

// sum initialized to 0

sum_even = 0;

sum_odd = 0;

cout << "This program calculates the sum of even and odd numbers which are positive. This program will end on invalid input." << endl;

cout << "Enter a positive number." << endl;

cin >> num;

// loop will terminate if the user inputs negative number

while( num >= 0 )

{

// for even numbers, input is added to sum_even else sum_odd

if( num%2 == 0 )

sum_even = sum_even + num;

else

sum_odd = sum_odd + num;

cout << "Enter a positive number." << endl;

cin >> num;

}

cout << sum_even << " " << sum_odd << endl;

return 0;

}

OUTPUT

This program calculates the sum of even and odd numbers which are positive. This program will end on invalid input.

Enter a positive number.

23

Enter a positive number.

34

Enter a positive number.

45

Enter a positive number.

67

Enter a positive number.

-69

34 135

User Dibbledeedoo
by
5.1k points