Skip to main content

C# for Loop

for loop is another powerful loop construct in C#. It is powerful and easy to use. for loop includes all three characteristics as initialization, termination and increment/decrement in a single line.


for (initialization; termination; increment / decrement) ;

Example:

using System;

namespace for_loop
{
  class Program
   {
     static void Main(string[] args)
      {
        int i;
        for (i = 0; i < 5; i++)
         {
           Console.WriteLine("For loop Example");
         }
        Console.ReadLine();
      }
   }
}


 Output

For loop Example
For loop Example
For loop Example
For loop Example
For loop Example


Nested for loop

 Sometimes, you are required to perform a task in nested loop condition. A loop within a loop is called nested loop. You can nested n number of loop as nested.

  Example:


using System;

namespace nested_loop
{
  class Program
   {
     static void Main(string[] args)
      {
        int i, j;
        for (i = 1; i <= 5; i++)
         {
           for (j = 1; j <= i; j++) //Nested for loop
            {
              Console.Write(j);
            }
           Console.Write("\n");
         }
        Console.ReadLine();
      }
   }
}

In the preceding example, the outer for loop won’t increment until inner for loop processes it’s all the cycles. Once the condition of inner for loop becomes false, the outer for loop increment by one and then again inner for loop does same work as previous.


Output



1
12
123
1234
12345






Comments