For loop is a control flow statement used to iterate a specific number of times, We can change loop behavior at any time.
Syntax
for (initialization; condition; iteration)
{
// Code to be executed during each iteration
}
Example 1
for (int i = 1; i < 6; i++)
{
Console.WriteLine("External Loop " + i);
}
This loop will run five times. Here's what happens during each iteration.
Iteration 1:
- i is initialized to 1.
- The condition i < 6 is true because 1 is less than 6.
- It prints "External Loop 1".
Iteration 2:
- i is incremented to 2.
- The condition i < 6 is true because 2 is less than 6.
- It prints "External Loop 2".
Iteration 3:
- i is incremented to 3.
- The condition i < 6 is true because 3 is less than 6.
- It prints "External Loop 3".
Iteration 4:
- i is incremented to 4.
- The condition i < 6 is true because 4 is less than 6.
- It prints "External Loop 4".
Iteration 5:
- i is incremented to 5.
- The condition i < 6 is true because 5 is less than 6.
- It prints "External Loop 5".
After this, i
is incremented to 6. Since 6 is not less than 6, the loop terminates, and the program moves to the next statement after the loop.
Result
External Loop 1
External Loop 2
External Loop 3
External Loop 4
External Loop 5
Example 2
Nested loop structure in C#, One loop inside of another loop.
for (int i = 1; i < 6; i++) // Outer Loop
{
Console.WriteLine("External Loop " + i);
for (int j = 0; j <= 5; j++) // Inner Loop
{
Console.WriteLine("Internal Loop " + j);
}
}
- Outer Loop: This loop iterates from 1 to 5 (i starts at 1 and ends when it's less than 6).
- Inner Loop: Inside each iteration of the outer loop, there's an inner loop that iterates from 0 to 5 (j starts at 0 and ends when it's less than or equal to 5).
Here's how the execution flows.
Iteration 1 of Outer Loop (i = 1):
Prints "External Loop 1".
Enters the Inner Loop:
Iterates from 0 to 5 and prints "Internal Loop 0" through "Internal Loop 5".
Iteration 2 of Outer Loop (i = 2):
Prints "External Loop 2".
Enters the Inner Loop again.
Iterates from 0 to 5 and prints "Internal Loop 0" through "Internal Loop 5".
This process continues until the outer loop finishes its iterations.
Overall, this nested loop structure will output a sequence of messages indicating both the current iteration of the outer loop and the iteration of the inner loop within each iteration of the outer loop.
Result
External Loop 1
Internal Loop 0
Internal Loop 1
Internal Loop 2
Internal Loop 3
Internal Loop 4
Internal Loop 5
External Loop 2
Internal Loop 0
Internal Loop 1
Internal Loop 2
Internal Loop 3
Internal Loop 4
Internal Loop 5
External Loop 3
Internal Loop 0
Internal Loop 1
Internal Loop 2
Internal Loop 3
Internal Loop 4
Internal Loop 5
External Loop 4
Internal Loop 0
Internal Loop 1
Internal Loop 2
Internal Loop 3
Internal Loop 4
Internal Loop 5
External Loop 5
Internal Loop 0
Internal Loop 1
Internal Loop 2
Internal Loop 3
Internal Loop 4
Internal Loop 5