Friday, 8 May 2015

For Loop example in c# .NET



What is For Loop:-
The for loop initialize the value before the first step. Then checking the condition against the current value of variable and execute the loop statement and then perform the step taken for each execution of loop body.




      






























For loop process flow diagram




Syntex of For loop:-

for(initialization; condition; step increment)
{
 code statement
}



c# Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleDemoApp
{
    class Test
    {
        static void Main(string[] args)
        {
          int count = 5;
          for(int i = 1; i <= count; i++)
          {  
           Console.WriteLine("For loop Iterate number is - " + i);
          }
           Console.ReadKey();
        }

    }
}


The output :-

















Infinite Loop
All of the expressions of the for loop statements are optional. A loop becomes infinite loop if a condition never becomes false. You can make an endless loop by leaving the conditional expression empty. The following statement is used to write an infinite loop.

 for(;;)
       { 
  // Code Statement…..
        }

Here the loop will execute infinite times because there is no initialization , condition and steps.


break and continue
We can control for loop iteration with the break and continue statements. Break terminates iteration and continue skips to the next iteration cycle.


            // Using Break

      static void Main(string[] args)
        {
          int count = 5;
          for(int i = 1; i <= count; i++)
          {  
              if (i == 3)
                {
                  Console.WriteLine("Continued at Iteration 3rd");
                  Break;
                }
              Console.WriteLine("For loop Iterate number is - " + i);
          }
           Console.ReadKey();
        }

The  output :-



      // Using Continue
        static void Main(string[] args)
        {
          int count = 5;
          for(int i = 1; i <= count; i++)
          {  
              if (i == 3)
                {
                  Console.WriteLine("Continued at Iteration 3rd");
                  Continue;
                }
              Console.WriteLine("For loop Iterate number is - " + i);
          }
           Console.ReadKey();
        }


The output :-















No comments:

Post a Comment