Part-9 C# Tutorial for & foreach-loop

For Loop :

The for loop is iteration statement into this loop.If there is a scenario where you need to execute any task for a specific times or "n" no of times then rather than writing that task to "n" times or you can use simply  loops to execute that task to "n" number of times.
So you can perform any repetitive task for "n" number of times then it is best practice to use Loops.

Syntax : Above, the for loop contains Three parts:
Variable Initialization, Conditional expression and Increment statement., which are Terminate by a semicolon.
  1. variable initialization: Declare & initialize a variable here which will be start from Ex= (int i = 0;).
  2. Condition: The condition is a boolean expression which will return either true or false. If the condition is true, the loop will start over again, if it is false, the loop will end.
  3. Increment Statement/Decrements Statement: The steps defines the incremental or decrement part. (;i++); (;i--);
Consider the following example of a simple for loop.





ForEach Loop

similar as for loops work, that doing any specific repetitive task but the difference is that here we cannot specify "iteration value" here value is decided automatically depending on total collection of arrays or list generic or array list or object collections. Value will be picked Automatically from these specified collections.

           foreach (var item in collection)
            {
                //logic 
            }

Example:-


class Program
{
static void Main(string[] args)
{
int[] data = new int[] { 1, 2, 3, 4, 5, 6, 7 };

foreach (var item in data)

{
Console.WriteLine("Value of i: {0}", item);
}
Console.Read();
}
}
Note:  foreach statement iterates through a collection.

Which is you prefer for loop() or foreach loop().

  • I prefer the FOR loop in terms of performance. FOREACH is a little slow when you go with more number of items.
  • If you perform more business logic with the instance then FOREACH performs faster.

Time took to loop:
  • FOREACH -> 2564.1405ms
  • FOR -> 2753.0017ms
Conclusion
If you do more business logic with the instance, then foreach() is recommended. If you are not doing much logic with the instance, then FOR is recommended.