Code

for loop

The for loop executes a block of code repeatedly until the condition is false. This type of loop is useful when the number of loop iterations is fixed (predetermined) and the counter variable that determines how many times the loop is going to be executed is needed in the loop.

for loop structure for loop execution order
for loop for loop execution order

for Loop example

If you have more than one statement within the loop, you must enclose the statements in opening and closing braces.

for (int i = 0; i <= 4; i++)
{
     Console.WriteLine("Some code executing here.");
     Console.WriteLine(i);
}

Run Demo

With a single statement

The following example demonstrates usage of a for loop. It writes out all the integers from 0 to 4. Curly brackets for the loop are optional, if there is only one statement in the code block.

for loop with single statement

Run Demo

OUTPUT

0
1
2
3
4

Infinite for Loop

Whenever you don’t give a condition to the loop, it automatically becomes an infinite loop meaning the loop block is executed endlessly. Use the double semicolon (;;) in for loop to make it run infinite times as shown below.

Note: To stop the loop press CTRL + C on the keyboard.

for (;;)
{
    Console.WriteLine("I am Infinite For Loop");
}

Run Demo

Nested for Loop

A loop contained within another loop is a nested loop. The innermost loop is executed more times than the outermost.

An inner loop can appear within an outer loop, this way:
Nested for Loop

Let’s see how two nested loops look like:

for (int i = 1; i <= 4; i++)
{
     for (int j = 1; j <= 2; j++)
     {
          Console.WriteLine(i + ", " + j);
     }
}

Run Demo

OUTPUT

1, 1
1, 2
2, 1
2, 2
3, 1
3, 2
4, 1
4, 2

break Statement

The break keyword causes the program to exit a loop prematurely, before it has completed its execution.

for loop break statement

In the below code, notice that the loop ends prematurely at break statement when the counter reaches 3 == 3. Without the break keyword, the loop should run from 1 to 4 because the loop condition is counter <= 4.

for (int counter = 1; counter <= 4; counter ++)
{
    if (counter == 3) // <- A 
        break;

    Console.WriteLine(counter);
}

Run Demo

OUTPUT

1
2

continue Statement

for loop continue statement

First we initialized the counter variable to run from 1 to 4. When counter = 3, the condition marked A evaluates to true. This causes for loop to skip rest of the current iteration and initiates the execution of the next iteration.

for (int counter = 1; counter <= 4; counter++)
{
    if (counter == 3) // <- A
        continue;

    Console.WriteLine(counter);
}

Run Demo

OUTPUT: 3 skipped

1
2
4

Add Comment

Click here to post a comment

Subscribe

Most Popular

Popular Video