tags:

views:

69

answers:

4

I want it to run three times but it actually never runs the loop and gets out. In VB 6.0 I could do that with a similar structure but how can I achieve the same thing with C# for loop? I want to to count down but it is not ALWAYS the case, sometimes I am passing "1" and sometimes "-1" for the step , when passed with "-1" it does not work

    for (int L = 3; L <= 1; L += -1)
    {
        MessageBox.Show("dfsdff");
    }
+4  A: 

It looks like your terminal condition of L <= 1 is what is throwing you off.

You probably meant to reverse that and say L >= 1. Otherwise when L is initialized to 3, and then the terminal is evaluated it would immediately return false saying that L is greater than 1, and therefore terminate your loop.

Jason Whitehorn
+1  A: 

the for loop can be written out as:

for(variable L = 3; as long as L satisfies condition L <= 1; increment L by -1)

Your L will always be greater than 1, so the loop never gets executed. The right way would be either:

for(int L = 0; L <= 2; L++)

or

for(int L = 2; L >= 0; L--)

if you want to start with 1, just modify accordingly.

Femaref
+5  A: 

Yes because you have the second clause (the "keep going whilst this is true" clause) the wrong way around, try this:

 for (int L = 3; L >= 1; L--)
    {
        MessageBox.Show("dfsdff");
    }

Now it says "start at 3", "decrement" (--) whilst L is bigger than or equal to 1.

winwaed
A: 

try this:

for (int L = 3; L >= 1; L--)
    {
        MessageBox.Show("dfsdff");
    }

That should count down for you, I've corrected it. They are correct, it was an infinite loop. Here is another way to do it, that might make more brain sense.

int L = 3
while( L > 0)
{
    MessageBox.Show("Your clever message);
    L--;
}
Chris
But it won't terminate!
codekaizen
That would countdown alright. Countdown for a very long time.
Jason Whitehorn
this will show infinite messageboxes.
Femaref
I don't think it will. Only once. L will be decremented to equal 2. Which then fails the test clause (which is never true).
winwaed
@winwaed, the author had previously written the terminal condition as `L <= 3`, which would have resulted in it looping for a very long time.
Jason Whitehorn
Ah okay - so it looks like he had 3 versions and I caught the correction to the version you commented on! :-)
winwaed