while loop to a for loop

I did my code but i didnt read that it had to be on for loop so how can I convert this to a fol-loop?

if (firstNum % 2 == 0)
counter = firstNum + 1;
else
counter = firstNum;

cout << "Odd integers between " << firstNum << " and "
<< secondNum << " are: " << endl;

while (counter <= secondNum)
{
cout << counter << " ";
counter = counter + 2;
}

cout << endl;
closed account (zb0S216C)
Use your nut. If you've learn't while loops, you should have learn't for loops.
1
2
for(int i(0U); i < secondNum; ++i)
    // ... 


Wazzak
Does this look right?


for (firstNum % 2 == 0; counter <= secondNum)
{
counter = firstNum + 1;
{counter = firstNum; counter = counter + 2;}


cout << "Odd integers between " << firstNum << " and "
<< secondNum << " are: " << endl;
Not quite, no. You should really read up on for-loops, but basically their construct is

for (intial value; while-condition; incrementer)

In your example, initial value will be assigning counter = firstNum.
Your while-condition will be the same as your original while-loop condition.
Your incrementer is your original counter = counter + 2, just moved into the for construct.

Jim
basically like this?

for (counter=firstNum; firstNum % 2 == 0; counter = counter + 2)
Almost ... your while-condition isn't quite right - it's the equivalent of

1
2
3
4
while (firstNum % 2 == 0)
{
   ...
}


which isn't what you're wanting.

Jim
I think i have got it here?

cout << "Odd integers between " << firstNum << " and "
<< secondNum << " are: " << endl;

for(;firstNum<= secondNum; firstNum+=2)
{
cout << firstNum<< " ";
}

cout << endl;
That would work, yes. Glad you realised you don't need the initialiser.

Note that in dropping the use of 'counter' and using 'firstNum' as the loop counter, after the loop you'll no longer know what the start point was, as you're incrementing it.

An alternate, still using counter, would be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (firstNum % 2 == 0)
  counter = firstNum + 1;
else
  counter = firstNum;

cout << "Odd integers between " << firstNum << " and "
<< secondNum << " are: " << endl;

for (; counter <= secondNum; counter += 2)
{
  cout << counter << " ";
}

cout << endl;


Jim
Thank you! Huge help!
Topic archived. No new replies allowed.