Learn for loop in C# programming with program examples and explanation with special notes. Demonstration of infinite loop and for each loop with C# code are included.

Topics

  • two formats syntax of for loop with example
  • Infinite for loop
  • Special note – semi colon after for ();{}

Syntax of for loop in C#

for(initialization; Boolean_expression; update/incremnt/decrement part)
{
//Statements
}

Code example:

public class Sample
    {

        public static void Main(String[] args) {
 
		int n = 0;
 
		for (n = 1; n <= 10; ++n) {

            Console.WriteLine(n);
		}
 
	}
    }

ANOTHER FOR LOOP FORMAT

Above code can also be written as below. notice that increment of variable in happening in body of the for loop in inside bracket e.g. for (n = 1; n <= 10; // missing)

 public class Sample
    {

        public static void Main(String[] args) {
 
		int n = 0;
 
		for (n = 1; n <= 10;) {

            Console.WriteLine(n);
            ++n;
		}
 
	}
    }

Infinite for loop in C#

Below syntax run a for loop for infinite time.

for ( ; ; )
{
}

Code example:

public class Sample
    {

        public static void main(String[] args) {
		
		for (; ;)
		{
            Console.WriteLine ("I am running infinitely...");	
		
		}
 
	}
    }


SPECIAL NOTE

Be careful with semi column [; ] after for () bracket before body. for example, for (n = 1; n <= 10; ++n);

Below code will execute for 10 times but will not go inside loop body.

public class Sample
    {

        public static void Main(String[] args) {
 
		int n = 0;
 
		for (n = 1; n <= 10;++n);
		{
            Console.WriteLine(n);	
		
		}
 
	}
    }

Below scenario Leads to hang if we use semicolon as for (n = 1; n <= 10;);{}.
In this scenario, increment is not written in for(), but in body.

public class Sample
    {

        public static void Main(String[] args) {
 
		int n = 0;
 
		for (n = 1; n <= 10;);
		{

            Console.WriteLine(n);			
	
			++n;
		}
 
	}
    }

Related Posts