The for loop is an entry-control loop as the condition is initially checked. It has the most efficient structure than the other two loops. The loop allows the programmer to write the execution steps together in a single line and also the specific number of times the execution is to be iterated.
for loop Flowchart:
It has three computing steps as shown in the syntax below.
- initialization: The first step is the initialization of the variable and is executed only once. And need to end with a semicolon(
;
). - condition: Second is condition check, it checks for a boolean expression. If true then enter the block and if false exit the loop. And need to end with a semicolon(
;
). - Increment or Decrement: The third one is the increment or decrement of the variable for the next iteration. Here, we do not need to use the semicolon at the end.
The syntax for for loop
in C#:
1 2 3 4 | for(initialization; condition; Increment/Decrement) { // Statements } |
You should use for a loop when the number of iterations is known beforehand, i.e. when the number of times the loop body is needed to be executed is known.
Example of C# for Loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | using System; namespace Loops { class ForProgram { static void Main(string[] args) { //f or loop execution for (int i = 1; i <= 10; i++) { Console.WriteLine("Value of i: {0}", i); } } } } |
Output:
1 2 3 4 5 6 7 8 9 10 | Value of i: 1 Value of i: 2 Value of i: 3 Value of i: 4 Value of i: 5 Value of i: 6 Value of i: 7 Value of i: 8 Value of i: 9 Value of i: 10 |