find and solve ||
Please wait.....

C# For Loop Example

If we know exactly that how many times we want to loop through a block of code, use the for loop instead of a while loop; The for loop executes a block of statements repeatedly until specified condition returns false.

for( initializer; condition; iterator)
    // code block

The for loop contains three sections, which are separated by a semicolon:

Initializer: This section is used to initialize a variable that will be local to a for loop and cannot be accessed outside loop. It can also be zero or more assignment statements, method call, increment or decrement expression e.g., i++, i--, and await expression.

Condition: This is a Boolean expression which will return either true or false. If an expression evaluates to true, then it will execute the loop again, otherwise the loop is exited.

Iterator: It defines incremental or decremental of the variable of loop.

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 from 0 to 8;

for(int I = 0;  I < 9;  i++)

Example explained

Statement 1 sets a variable before the loop starts ( int I = 0).

Statement 2 defines the condition for the loop to run ( I must be less than 9). If the condition is true, the loop will start over again, if it is false, the loop will end.

Statement 3 increases a value( i++) each time the code block in the loop has been executed.

Another example

The given example will print even values between o to 18;

for( int I = 0; I <=18; I = i+2)

C# for Loop full code

using System;
namespace LoopExample
 class ForLoopExample
  public static void Main(string[] args)
   for (int i=1; i<=4; i++)
    Console.WriteLine("C# For Loop Example: Iteration {0}", i);
C# For Loop Example: Iteration 1
C# For Loop Example: Iteration 2
C# For Loop Example: Iteration 3
C# For Loop Example: Iteration 4
  • initialization statement is int i=1
  • condition statement is i<=5
  • iterator statement is i++

How for loop works?

  • C# for loop has three statements: initialization, condition and iterator.
  • The initialization statement is executed at first and only once. Here, the variable is usually declared and initialized.
  • Then, the condition is evaluated. The condition is a boolean expression, i.e. it returns either true or false.
  • If the condition is evaluated to true:

          #. The statements inside the for loop are executed.

          #. Then, the iterator statement is executed which usually changes the value of the initialized variable.

          #. Again the condition is evaluated.

          #. The process continues until the condition is evaluated to false.

  • If the condition is evaluated to false, the for loop terminates.