Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a simple problem with ForLoop in C#

Tags:

c#

for-loop

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");
    }
like image 743
Bohn Avatar asked Dec 07 '22 01:12

Bohn


2 Answers

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.

like image 135
winwaed Avatar answered Dec 09 '22 15:12

winwaed


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.

like image 33
Jason Whitehorn Avatar answered Dec 09 '22 13:12

Jason Whitehorn