Simple while question

1
2
3
4
5
6
7
8
if (num1 > num2)
      {
 while (num1 > num2)
                 {   
                     num2++;
                     cout << num2 <<endl;
                        }
                    }


If I input 20 for num1 and 10 for num2 why does it print from 11 to 20 instead of 11 to 19? I want it to print from 11 to 19. I know this is just some logic fail from me but I can't seem to know what it is. Thanks for your help
Because you at first increase num2 and only after that you print it. That is inside the condition num2 that is equal to 19 is less than num1 (20)/ So the control will be passed inside the loop. Then you increase the num2 and num2 becomes equal to 20. This value is outputed.

You could change your loop the following way

while ( num1 > ++num2 ) cout << num2 << endl;
Thank you, it fixed it and I wonder how I couldn't see that...
Hey I have another question what if I wanted to increase more than 1? It only works if I use ++; but If I use +=2 an error shows up saying:

"non-lvalue in assignment"
Last edited on
You get that error when you write num2 += 2;?
I get that error when I write num2 +=2 when I write num2 +=2; I get that one and a bunch of

expected `)' before ';' token
expected primary-expression before ')' token
expected `;' before ')' token
closed account (17pz3TCk)
Could you post all of your code so we could examine it?
Topic archived. No new replies allowed.