maximida
maximida

Reputation: 15

For loop not being executed second time around in a while loop

I'm just a beginner in C++. I'm writing small and simple program that prints a series of integers between two user-specified integers.

At the end, the program will re-run the while loop if the user returns 1, but when that happens the program will not print the series of numbers again (the for loop doesn't work).

Here's the source code:

int main(void)
{
    int num1, num2;
    int doContinue = 1;

    while (doContinue == 1)
    {
        cout << "Please enter two integers, the first being the smallest: ";

         do { //does everything in curly braces while the user inputs the numbers wrong...
                cin >> num1 >> num2;

                if (num1 > num2)
                    {
                        cout << "Your first number was bigger than the second.\nTry again!: ";
                    }

            } while (num1 > num2);//... but once it's not wrong, break out of this do loop

        //at this point the input has been checked, so we can proceed to print the series

        for(int num1; num1 <= num2; num1++)
            {   
                cout << num1 << " \n";
            }

        cout << "Would you like to compute another series of integers? 1=yes, anything else=no: ";
        cin >> doContinue;
    }

    return 0;
}

Upvotes: 0

Views: 1094

Answers (3)

Nasser Ghazali
Nasser Ghazali

Reputation: 21

change this part of code

for(int num1; num1 <= num2; num1++)
            {   
                cout << num1 << " \n";
            }

to

for( ; num1 <= num2; num1++)
            {   
                cout << num1 << " \n";
            }

Upvotes: 0

Billy ONeal
Billy ONeal

Reputation: 106530

Your code exhibits undefined behavior.

    for(int num1; num1 <= num2; num1++)
        {   
            cout << num1 << " \n";
        }

creates a new integer called num1, unrelated to the num1 outside of the for loop. You do not initialize the value of num1, but proceed to make comparisons against it.

Remove int num1 (that is, something like for(; num1 <= num2; num1++)) in your for loop and try again.

Upvotes: 2

talnicolas
talnicolas

Reputation: 14053

Try

for(int i = num1; i<= num2; i++)

instead of

for(int num1; num1 <= num2; num1++)

Upvotes: 0

Related Questions