You will need to use 2 loops. The first loops the odd numbers using a starting value of 1, while the second loops the even numbers using a starting value of 2. At the end of every cycle, add 2 to the number.
In this case, you're better using a regular while loop to protect against the user entering 1, since using a do while always executes the code at least once, but if you do use a do while loop, you will just need an if statement in the second loop to check if the user entry was 1.
#include <iostream>
usingnamespace std;
int main ()
{
int num;
int odd=1;
int even=2;
cout << "Please enter an integer: " << endl;
cin >> num;
do
{
cout << "Odd numbers from 1-" << num << " " << odd << endl;
odd=odd+2;
}while (odd<num);
system ("pause");
return 0;
}
but the cout keeps popping up. Is it possible to make it appear just only once?
Like This:
Odd numbers from 1 - 10: 1 3 5 7 9
The only "error" I found is that it keeps prompting me to enter another integer after I entered an integer. But I "fixed" this by putting system("pause") and return 0; inside the loop. Is such a thing acceptable or are there any better workarounds?
@sanasuke15
The only "error" I found is that it keeps prompting me to enter another integer after I entered an integer. But I "fixed" this by putting system("pause") and return 0; inside the loop
It is not a fix. It is a stupidy. The original program allows to test the output for any arbitrary integer value and if you want to exit the loop it is enough to enter 0.
The error is that the program does not check whether i += 2 results in overflow for type unsigned int.
break wouldn't solve it, if you don't want something to appear multiple times, make sure it isn't in a loop, in the last full attempt you posted, you had
cout << "Odd numbers from 1-" << num << " " << odd << endl;
inside the loop, so it will print the entire statement as many times as it needs. You only want to be odds to be looping in that case, so all that should be inside the loop is cout << " " << odd;, move the stuff before that space above the loop, and the endl below the loop.