for

Loops 20 times, from 1 to 20

for (int i = 1; i <= 20; i++) 
{
   break; //terminates the closest ending loop or switch
}

Loops 10 times, starting from 0 to 19, increment by 2

for (int i = 0; i < 20; i += 2) 

for (reverse)

If you want to decrement by 1

for (int i = 20; i > -1; i--) 
{
}

Loops 10 times, starting from 20 to 1, decrement by 2

for (int i = 20; i > 0; i -= 2) 

Break

This will jump out of the loop when i is equal to 4.

for (int i = 0; i < 10; i++) 
{
  if (i == 4)
  {
    break;
  }
  Console.WriteLine(i);
}

Continue

The continue statement transfers execution to the next iteration within the loop

for (int i = 2; i <=10; i++) 
{
   if (i = 6)
   {
      continue;
   }
}

Single Statement

When you only have a single statement the curly bracket is optional.


No Statements

You can have a for loop with no statements. This is like a while true loop

for (; ; ) 
{
}

Example - With An Array

Using it with an array

string[] myArray = { "one", "two", "three" } 
for (int i = 0; i < myArray.Length; i++)
{
   Console.Write(myArray[i]);
}

Example - Through Lowercase Letters


for (char c = 'a'; c <= 'z'; c++) 
{
    Console.WriteLine(c);
}

Example - Two Variables at Once


for (int i = 0, x = 0; i < 10 && x >= -2; i++, x--) 
{
    System.Console.WriteLine("for loop: i={0}, x={1}", i, x);
}

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext