For Loop:
General Syntax:
For Each Loop:
General Syntax:
It’s preferred when you know how many iteration you want. It is used to executes a block of statements for as long as a specified condition is true.
General Syntax:
for(Initialization; Test Condition; Increment)
{
Statement;
}
{
Statement;
}
Example: To add the number from 1 to 10 by using for loop and sum the number by series of 1+2+3+...+10.
using System;
using System.Collections.Generic;
using System.Text;
namespace for_loop
{
class Program
{
static void Main(string[] args)
{
int[] arry = new int[] {1,2,3,4,5,6,7,8,9,10 };
int s = 0;
for (int i = 0; i < arry.Length; i++)
{
s = s+ arry[i];
}
Console.WriteLine("Sum is: {0}",s);
Console.ReadKey();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace for_loop
{
class Program
{
static void Main(string[] args)
{
int[] arry = new int[] {1,2,3,4,5,6,7,8,9,10 };
int s = 0;
for (int i = 0; i < arry.Length; i++)
{
s = s+ arry[i];
}
Console.WriteLine("Sum is: {0}",s);
Console.ReadKey();
}
}
}
Output : Sum is:55
For Each Loop:
It operates on collections of items, for instance arrays or other built-in list types. It does not use an integer index. Instead, it is used on a collection and returns each element in order. In the foreach-statement, you do not need to specify the loop bounds minimum or maximum. It traverse whole collection.
General Syntax:
foreach( Datatype item in items )
{
Statement;
}
{
Statement;
}
Example: To add the number from 1 to 10 by using foreach loop and sum the number by series of 1+2+3+...+10.
using System;
using System.Collections.Generic;
using System.Text;
namespace for_loop
{
class Program
{
static void Main(string[] args)
{
int[] arry = new int[] {1,2,3,4,5,6,7,8,9,10 };
int s = 0;
foreach (int i in arry)
{
s = s+ i;
}
Console.WriteLine("Sum is: {0}",s);
Console.ReadKey();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace for_loop
{
class Program
{
static void Main(string[] args)
{
int[] arry = new int[] {1,2,3,4,5,6,7,8,9,10 };
int s = 0;
foreach (int i in arry)
{
s = s+ i;
}
Console.WriteLine("Sum is: {0}",s);
Console.ReadKey();
}
}
}
Output : Sum is:55
Conclusion:
Both the concepts are same only. For each is used for traversing items in a collection. It usually maintain no explicit counter and no use of index. They essentially say "do this to everything in this set", rather than "do this x times".
For loop is classified as an iteration statement. The statements in the for loop repeat continuously for a specific number of times. It as counter and integer index (ex: a[i], i represent the index value and change it by increment operation on each iteration).