![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
Hobbyist Programmer
Join Date: Mar 2005
Posts: 148
Rep Power: 4
![]() |
I don't get it
If I write this code(which outputs the numbers 1 to 10 and each number's square) it runs fine:
int counter = 1; do { cout << counter << "\t" << counter * counter << endl; }while(++counter <= 10) As I said above it outputs 1 to 10 and each numbers square. But if I change the way I increment the control variable to counter++ so it looks like this: int counter = 1; do { cout << counter << "\t" << counter * counter << endl; }while(counter++ <= 10) It actually outputs all numbers plus and including 11 and it's square. I don't understand why that is. It seems to me that it shouldn't matter because either way when 10 gets incremented to 11 it should cause the test condition to fail, meaning the last number output should still be 10. Please explain what's goin on here. I'm just a beginner(again). |
|
|
|
|
|
#2 |
|
Programming Guru
![]() Join Date: Oct 2004
Location: namespace std
Posts: 1,246
Rep Power: 5
![]() |
because when you put the ++ afterwards it looks at the last 10, says ok, we're still good for the looping condition, THEN it increments the variable and does the loop again. it doesn't TEST the 11 until it comes back around. this is a valuable lesson indeed and would be a great post for all beginners to read. thanks. :-)
__________________
i put on my robe and wizard hat... Have you ever heard of Plato, Aristotle, Socrates?...Morons. |
|
|
|
|
|
#3 |
|
Newbie
Join Date: Apr 2005
Posts: 15
Rep Power: 0
![]() |
Thats a great question and I found it tested in two consecutive programming classes in college. Like ninja said with the ++ after the variable it does everything else in the line (including the test for the while loop) then increments but if its before the variable, then the increment is the first thing done in the line. Sorry about being repetitive but I wanted to emphasize the fact that professors love testing on this guy.
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|