C# For Loop
To iterate a specified code for multiple times, the C# for loop is used. It is recommended to use the For loop when the number of iterations is fixed. The syntax and behavior of C# for loop are the same as that in C or C++; the variable is firstly initialized, the conditions are then checked and finally, the value of the variable is increased or decreased.
Syntax:
for (initialization; condition; increase/decrease) { //code to be executed }
Example:
using System; public class Example { public static void Main(string[] args) { for(char x='a'; x<='p'; x++) { Console.WriteLine(x); } } } |
Output:
Explanation:
In the above example, we are using a simple program to display the use of the For loop in C#.
C# Nested For Loop:
When a For loop is used inside another For loop, then it is called nested For loop in C#. The outer loop of a nested For loop is executed only one time when the inner loop of the nested For loop is completely executed, i.e, if the outer loop is executed 3 times and the inner loop is executed 5 times, then the inner loop will be executed 5 times for each outer loop i.e. total 15 times.
Example:
using System; public class Example { public static void Main(string[] args) { for(char x='a'; x<='d'; x++) { for(int y=1; y<=4; y++){ Console.WriteLine(x+ " "+ y); } } } } |
Output:
Explanation:
In the above example, we are using a simple program to display the use of the Nested for loop in C#.
C# Infinite For Loop:
To execute a For loop for the infinite times, the double semicolon is used in for loop, and such a loop is called Infinite For loop in C#.
Example:
using System; public class Example { public static void Main(string[] args) { for (; ;) { Console.WriteLine("Stop Me if you can!!"); } } } |
Output:
Explanation:
In the above example, we are using a simple program to display the use of infinite for loop in C#.