pharmacyguy42
pharmacyguy42

Reputation: 29

Don't understand why this loop doesn't iterate

Not sure what I am doing wrong here. I am new to C# and am trying to convert VB.Net code from an online tutorial. I can't get this For loop to iterate:

if (Screens.Count > 0)
{
    for (int i = Screens.Count - 1; i == 0; --i)                
    {
        if (Screens[i].GrabFocus==true)
        {
            Screens[i].Focused = true;
            DebugScreen.FocusScreen = "Focused Screen: " + Screens[i].Name;
            break;
        }
    }
}

There are 2 screens in the list. The second screen (Screens[1]) has GrabFocus set to true. During debugging, execution jumps from line 3 (for ...) right to the last closing brace. The nested "If" statement never executes. Also, I think the break statement is wrong because I am actually trying to end the "For" loop.

Upvotes: 0

Views: 110

Answers (4)

Christos
Christos

Reputation: 53958

You haven't written correctly your for loop. You should replace it with the following:

for (int i = Screens.Count - 1; i >=0; --i)   

You start from the value Screens.Count - 1 and you decrease by 1 the i in each step, until i becomes equal to zero. Then you stop.

Generally speaking, the correct syntax is the following:

for (initializer; condition; iterator)
    body
  • The initializer section sets the initial conditions. The statements in this section run only once, before you enter the loop. The section can contain only one of the following two options.
  • The condition section contains a boolean expression that’s evaluated to determine whether the loop should exit or should run again.
  • The iterator section defines what happens after each iteration of the body of the loop. The iterator section contains zero or more of the following statement expressions, separated by commas
  • The body of the loop consists of a statement, an empty statement, or a block of statements, which you create by enclosing zero or more statements in braces.

For more information about this, please have a look here.

What's the problem in your case?

The second bullet. The condition, i==0 is false by the begin. Hence the loop will not be executed at all.

Upvotes: 4

user3323654
user3323654

Reputation: 88

Your for loop is not correct. Here's is the code

if (Screens.Count > 0)
      {
         for (int i = Screens.Count - 1; i >= 0; --i)                
         {
            if (Screens[i].GrabFocus==true)
            {
                Screens[i].Focused = true;
                DebugScreen.FocusScreen = "Focused Screen: " + Screens[i].Name;
                break;
            }
         }
      }

Upvotes: -1

Tushar Gupta
Tushar Gupta

Reputation: 15923

i == 0 should be replaced with i >= 0

for (int i = Screens.Count - 1; i >=0; --i)  

Upvotes: 0

Mitch Wheat
Mitch Wheat

Reputation: 300559

i == 0 should be i >= 0

i.e.

for (int i = Screens.Count - 1; i >= 0; --i)  

Upvotes: 0

Related Questions