Help!

I don't really understand "while" control structure with (--) and (++). Here's what I learned about "while":
- If ( 4 > 0 ) is true, then the statements will execute.
- if its false, it ignores.
- the number 10 will loop 10 in ( 4 > 10 )? (I'm not sure) :(
- it must have a "while (expression) statement"

That's all I got. :\ So yeah.......Help :(
Last edited on
Dude, buy a book. You have made enough threads for me to notice you.
I already got a book. And no! >:(
Your question makes no sense.
Well english isn't my first language... so anyways, my question: Explain what -- and ++ does in while...
while is a pre-test conditional loop:
1
2
3
4
while (/*this evalutates to true*/
{
  //Do this
}


Putting a ++ or -- within the while condition is probably something to focus on when you understand loops more, but here's a simple one:
1
2
3
4
5
6
7
8
9
int i  = 10;
cout << "Before the loop, i equals: " << i << endl;
cout << "Start loop\n";
while (i--)
{
  cout << "i equals: " << i << endl;
}
// Note the value of i after the loop
cout << "After the loop i equals: " << i << endl


What is important to note is that even though the expression is false when i = zero, the -- operator still happens. Leaves i = -1

Edit:
Explain what -- and ++ does in while

Same thing they do every where else.
Last edited on
Something that should be clarified a bit is that as long as a variable doesn't equal 0, it evaluates true. if (5) since 5 isn't 0, it's true, and the if condition is met. So looking at the code again, i will decrements only after it's evaluated. So when i = 1, the while statement looks like this while (1) but since the -- comes after the variable i, after the while condition evaluates to true, i is reduced to 0 and is still used in the body of the loop. The next pass, while (0) evaluates false (0 is false, all non zero values are true) so the loop terminates, but since there is still a decrement operator with i, it also decrements i making i result to -1.

Hope this helps.
Topic archived. No new replies allowed.