C Sharp For Loop

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# For Loop

The C# for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop than while or do-while loops.

The C# for loop is same as C/C++. We can initialize variable, check condition and increment/decrement value.

Syntax:

  1. for(initialization; condition; incr/decr){  
  2. //code to be executed  

Flowchart:

C# for loop flowchart

C# For Loop Example

  1. using System;  
  2. public class ForExample  
  3.     {  
  4.       public static void Main(string[] args)  
  5.       {  
  6.           for(int i=1;i<=10;i++){    
  7.             Console.WriteLine(i);    
  8.           }    
  9.       }  
  10.     }  

Output:

1
2
3
4
5
6
7
8
9
10

C# Nested For Loop

In C#, we can use for loop inside another for loop, it is known as nested for loop. The inner loop is executed fully when outer loop is executed one time. So if outer loop and inner loop are executed 3 times, inner loop will be executed 3 times for each outer loop i.e. total 9 times.

Let's see a simple example of nested for loop in C#.

  1. using System;  
  2. public class ForExample  
  3.     {  
  4.       public static void Main(string[] args)  
  5.       {  
  6.         for(int i=1;i<=3;i++){    
  7.                 for(int j=1;j<=3;j++){    
  8.                     Console.WriteLine(i+" "+j);    
  9.                 }    
  10.         }    
  11.       }  
  12.     } 

Output:

1 1
1 2
1 3
2 1
2 2 
2 3
3 1
3 2
3 3

C# Infinite For Loop

If we use double semicolon in for loop, it will be executed infinite times. Let's see a simple example of infinite for loop in C#.

  1. using System;  
  2. public class ForExample  
  3.     {  
  4.       public static void Main(string[] args)  
  5.       {  
  6.           for (; ;)  
  7.           {  
  8.                   Console.WriteLine("Infinitive For Loop");  
  9.           }    
  10.       }  
  11.  }  

Output:

Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
ctrl+c