C++ -Need some help please [message #8102] |
Sat, 26 July 2003 18:29 |
Nazma Bepat
Messages: 34 Registered: May 2003
|
Member |
|
|
Shawab,
Thanks for helping me out earlier with C++. I am trying to understand the difference between preincrement and postincrement. Is it possible for you to look at the following code and let me know the value of total when exiting each of the following while repetition structures (enter your answer after each while repetition structure):
int x = 1, total = 0;
while ( ++x <= 5 ) {
total += x;
}
int x = 1, total = 0;
while ( x++ <= 5 ) {
total += x;
}
|
|
|
Re: C++ -Need some help please [message #8108 is a reply to message #8102] |
Sun, 27 July 2003 23:58 |
|
Maaher
Messages: 7065 Registered: December 2001
|
Senior Member |
|
|
It's been a long time since I've done any C++, but I believe the outcome is this:
1. 14 ( 2 + 3 + 4 + 5 )
2. 20 ( 2 + 3 + 4 + 5 + 6 )
In the first statement you increment x, evaluate it and in the loop add x to total.
In the second statement, you evaluate x against 5, increment it and in the loop add x to total. This makes that the second statement performs an extra loop.
At least, that's what I assume. You do know you can download a free copy of the old DOS compiler Borland Turbo C++ from http://bdn.borland.com/museum, or from this page directly?
MHE
|
|
|