39.3k views
3 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, on a line by itself and separated by spaces, the sum of all the even integers read, the sum of all the odd integers read, a count of the number of even integers read, and a count of the number of odd integers read, all separated by at least one space. Declare any variables that are needed.

User Thomee
by
6.3k points

1 Answer

5 votes

Answer:

The loop for the given scenario is shown.

while( num >= 0 )

{

if( num%2 == 0 )

{

sum_even = sum_even + num;

count_even = count_even + 1;

}

else

{

sum_odd = sum_odd + num;

count_odd = count_odd + 1;

}

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

cin >> num;

}

Step-by-step explanation:

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

int sum_even, sum_odd, count_even, count_odd, num;

The sum variables are initialized.

sum_even = 0;

sum_odd = 0;

count_even = 0;

count_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 and count of even numbers is displayed followed by the sum of negative numbers.

cout << sum_even << " " << sum_odd << " " << count_even << " " << count_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, count_even, count_odd, num;

// sum initialized to 0

sum_even = 0;

sum_odd = 0;

count_even = 0;

count_odd = 0;

cout << "This program calculates the sum and count 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;

count_even = count_even + 1;

}

else

{

sum_odd = sum_odd + num;

count_odd = count_odd + 1;

}

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

cin >> num;

}

cout << sum_even << " " << sum_odd << " " << count_even << " " << count_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.

56

Enter a positive number.

78

Enter a positive number.

91

Enter a positive number.

-4

134 114 2 2

User Carola
by
5.9k points