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;
}
Your code exhibits undefined behavior.
creates a new integer called
num1, unrelated to thenum1outside of the for loop. You do not initialize the value ofnum1, but proceed to make comparisons against it.Remove
int num1(that is, something likefor(; num1 <= num2; num1++)) in your for loop and try again.