C# – Looping with the For Iteration Statement

If you ever in Visual Studio, write down ‘for’ and tip two times ‘tab’ on keyboard, you will be seeing that for Iteration statement would be created for you.

for(int i=0; i <10; i++){

  //your code

}

i – any variable name

1st part – counter declaration, can be initialized to any number

2nd part – condition, can be any expression that equates to a bool

3nd part – increment i++ / decrement i–, can step more than i using +=.

string[] names = new string[]{"John", "Paul", "Josh"};

for(int i = 0; i<names.Length; i++){

//can search for a specific value

if(names[i] == "Josh"){
//do something here
// can break out additional iterations if need to
break;
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: