Write a loop that reads positive integers from standard input, printing out those values that are greater than 100, and that terminates when it reads an integer that is not positive. The values should be separated by single blank spaces. Declare any variables that are needed. in c++
The Correct Answer and Explanation is :
Here is the C++ code that accomplishes what you’re asking for:
#include <iostream>
using namespace std;
int main() {
int num; // Variable to store each input number
bool first = true; // Flag to check if this is the first number to print
// Start a loop that will run indefinitely until a non-positive number is entered
while (true) {
cin >> num; // Read a number from the user
// Check if the number is positive
if (num <= 0) {
break; // Exit the loop if the number is not positive
}
// Print the number if it is greater than 100
if (num > 100) {
if (!first) {
cout << " "; // Print a space before the next number, but not before the first one
}
cout << num; // Print the number
first = false; // After the first number, the flag is set to false
}
}
cout << endl; // Print a newline at the end for better output formatting
return 0; // Exit the program successfully
}
Explanation:
- Variables:
int num;: This variable stores the number that will be read from the user input.bool first = true;: A flag to determine if the current number is the first number to be printed. This is necessary for proper formatting since numbers must be separated by spaces but should not start with one.
- Input and Looping:
- We use an infinite
while (true)loop that keeps reading numbers until a non-positive integer is entered. - Inside the loop, the program reads an integer using
cin >> num.
- We use an infinite
- Termination Condition:
- If the entered number is less than or equal to zero (
num <= 0), the loop is terminated usingbreak.
- If the entered number is less than or equal to zero (
- Checking Conditions:
- If the number is greater than 100 (
num > 100), the program prints it. If it’s not the first number, it prints a space before the number for proper formatting.
- If the number is greater than 100 (
- Output Formatting:
- A space is printed before any number except the first one using the
firstflag, which ensures that no extra spaces appear at the beginning of the output. - After all numbers are printed, a newline is printed to ensure the output is neatly formatted.
- A space is printed before any number except the first one using the
- End of Program:
- The program finishes execution and returns 0 to indicate successful completion.
Example Input and Output:
Input:
101
150
99
200
-1
Output:
101 150 200
This solution efficiently handles the task by keeping track of when to print spaces and ensures that input stops when a non-positive number is encountered.