The biggest differences are that a foreach loop processes an instance of each element in a collection in turn, while a for loop can work with any data and is not restricted to collection elements alone. This means that a for loop can modify a collection - which is illegal and will cause an error in a foreach loop.
The for loop executes a statement or a
block of statements repeatedly until a specified expression evaluates to
false. there is need to specify the loop bounds( minimum or maximum).
int j = 0;
for (int i = 1; i <= 5; i++)
{
j
= j + i ;
}
{
j
= j + i ;
}
The foreach statement repeats a group of
embedded statements for each element in an array or an object
collection.you do not need to specify the loop bounds minimum or
maximum.
int j = 0;embedded statements for each element in an array or an object
collection.you do not need to specify the loop bounds minimum or
maximum.
int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8,
13 };
foreach (int i in tempArr )
{
j = j + i ;
}
No comments:
Post a Comment