76.9k views
1 vote
All values fit a category? C++

Declare a Boolean variable named allPositive. Then, read integer numVals from input representing the number of integers to be read next. Use a loop to read the remaining integers from input. If all numVals integers are positive, assign allPositive with true. Otherwise, assign allPositive with false.
Code at the end of main() outputs "All match" if allPositive is true or "Not all match" if allPositive is false.
Ex: If the input is:
3
90 95 35
then the output is:
All match
Note: Positive integers are greater than zero.
-----------------------
#include
using namespace std;

int main() {
int numVals;
/* Additional variable declarations go here */

/* Your code goes here */

if (allPositive) {
cout << "All match" << endl;
}
else {
cout << "Not all match" << endl;
}

return 0;
}

1 Answer

4 votes

Answer:

#include <iostream>

using namespace std;

int main() {

int numVals;

bool allPositive = true;

int inputVal;

cout << "Enter the number of integers: ";

cin >> numVals;

for (int i = 0; i < numVals; i++) {

cin >> inputVal;

if (inputVal <= 0) {

allPositive = false;

}

}

if (allPositive) {

cout << "All match" << endl;

}

else {

cout << "Not all match" << endl;

}

return 0;

}

Step-by-step explanation:

The program first declares a variable allPositive of type boolean and initializes it to true. Then it reads an integer numVals from input representing the number of integers to be read next. Using a loop, it reads the remaining integers one by one and checks if each integer is positive (greater than 0). If any integer is not positive, allPositive is set to false. Finally, the program outputs "All match" if allPositive is true and "Not all match" if allPositive is false.

User Davidfowl
by
8.2k points