LogIn
I don't have account.

for loop in c#

DevSniper
188 Views

for(Statement 1; Statement 1; Statement 3)
{  
   // code block
}
  • for loop
  • Infinite for Loop
  • nested for loop
  • for loop is used to execute a block of code several times
  • for loop is a entry control loop it verifies condition before executing of code block.
  • Statement 1 :- it execute once before execution of the code block. basically here we perform initialization.
  • Statement 2 :- it execute before every execution of the code block. Here we define condition of the execution of code block. if the condition is false we stop execution of the code blcok.
  • Statement 3 :- it execute after every execution of the code block.

For Loop

Example 1
using System;

class Program
{
    static void Main()
    {
        for(int i=3; i<10; i++) {
            Console.WriteLine(i);
        }
    }
}
3
4
5
6
7
8
9
Example 2
using System;

class Program
{
    static void Main()
    {
        int i=10,n=50;
        for(; i<n; i++) {
            if(i%5==0)
                Console.WriteLine(i);
        }
    }
}
10
15
20
25
30
35
40
45

Infinite For Loop

if we keep statement 2 (condition) empty OR define a condition that never becomes false, loop become Infinite Loop

Example : Empty condition case
for( ; ; ) 
{
   // Code block
}
OR
for(int i=5 ; ;) 
{
   // Code block
}
OR
for(int i=5 ; ;i++) 
{
   // Code block
}
Example : Define condition that never becomes false
for( int i=1 ; i>0; i++ ) 
{
    //Code block
}
Nested For Loop

if we place one loop inside other for loop this is called nested for loop. inner for loop executed fully for every outer for loop execution.

using System;

class Program
{
    static void Main()
    {
        for( int i=1 ; i<=2; i++ ) {
            Console.WriteLine($"Inside Outer loop i : {i}");
            for(int j= 1; j<=3 ; j++) {
                Console.WriteLine($"\tinside inner loop i :- {i} and j : {j}");
            }
        }
    }
}
Inside Outer loop i : 1
	inside inner loop i :- 1 and j : 1
	inside inner loop i :- 1 and j : 2
	inside inner loop i :- 1 and j : 3
Inside Outer loop i : 2
	inside inner loop i :- 2 and j : 1
	inside inner loop i :- 2 and j : 2
	inside inner loop i :- 2 and j : 3