C# For Loop

If you know exactly how many times you want to enter a code block, use a for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) 
            {
              // code block to be executed
            }
            

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) 
            {
              Console.WriteLine(i);
            }
            

Another Example

This example will only print equal values ​​between 0 and 10:

Example
for (int i = 0; i <= 10; i = i + 2) 
            {
              Console.WriteLine(i);
            }
            

The foreach Loop

There is also a foreach loop, which is only used to loop through in the array:

Syntax
foreach (type variableName in arrayName) 
            {
              // code block to be executed
            }
            

The following example removes all elements from the cars array, using a foreach loop:

Example
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
            foreach (string i in cars) 
            {
              Console.WriteLine(i);
            }