Jose Luis Landivar Jose Luis Landivar - 2 months ago 13
C++ Question

On C++ run program if correct otherwise ask input again

I'm new into programing. I'm working on a program that will tell the odd and even numbers that are less or equal to the user's input (for inputs >=0). How do I make the program run if value is >=0 and ask for the input again if the value is <0.
Here is the program:

> #include <iostream>
using namespace std;
int main() {
cout << "Please enter only a positive value\n";
// Get number from user
int input = 0;
cout << "Enter a number:\n";
cin >> input;
int number = 1;
while (input >= 0 && number <= input) {
// Print some numbers
cout << "Here are some odd numbers:\n";
while (number <= input) {
cout << number << endl;
number = number + 2;
}
// Print some numbers
cout << "Here are some even numbers:\n";
int number2 = 0;
while (number2 <= input) {
cout << number2 << endl;
number2 = number2 + 2;
}
}
return 0;
}

Answer

Correct code:

#include <iostream>
using namespace std;
int main() {
    cout << "Please enter only a positive value\n";
    // Get number from user
    int input = 0;
    cout << "Enter a number:\n";
    cin >> input;
    while (input < 0) {
        cout << "Input is negative. Enter again: \n";
        cin >> input;
    }
    int number = 1;
    while (input >= 0 && number <= input) {
        // Print some numbers
        cout << "Here are some odd numbers:\n";
        while (number <= input) {
            cout << number << endl;
            number = number + 2;
        }
        // Print some numbers
        cout << "Here are some even numbers:\n";
        int number2 = 0;
        while (number2 <= input) {
            cout << number2 << endl;
            number2 = number2 + 2;
        }
    }
    return 0;
}

Note that I added this chunk:

while (input < 0) {
     cout << "Input is negative. Enter again: \n";
     cin >> input;
}

to handle negative inputs.