The for loop:
- The for loop's variable always be integer only.
- The For Loop executes the statement or block of statements repeatedly until specified expression evaluates to false.
- In for loop we have to specify the loop's boundary ( maximum or minimum).-------->We can say this is the limitation of the for loop.
- It iterate either forward or backward directions like
for(int =5; i > = 0; i--)
{
}
for(int =0; i < 5; i++)
{
}
The foreach loop:
- In the case of the foreach loop the variable of the loop while be same as the type of values under the array.
- The Foreach statement repeats a group of embedded statements for each element in an array or an object collection.,ie, It iterate over collections for each & every elements.
- In foreach loop, You do not need to specify the loop bounds minimum or maximum.---> here we can say that this is the advantage of the for each loop.
- It iterate over collections only forward direction.
Or,
- 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 ;
- }
- int j = 0;
- int[] myArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };
- foreach (int i in myArr )
- {
- j = j + i ;
- }
- foreach: Treats everything as a collection and reduces the performance. foreach creates an instance of an enumerator (returned from GetEnumerator()) and that enumerator also keeps state throughout the course of the foreach loop. It then repeatedly calls for the Next() object on the enumerator and runs your code for each object it returns.
Using for loop we iterate the array in both direction, that is from index 0 to 9 and from 9 to 0.
But using for-each loop, the iteration is possible in forward direction only. - In variable declaration, foreach has five variable declarations (three Int32 integers and two arrays of Int32) while for has only three (two Int32 integers and one Int32 array).
When it goes to loop through, foreach copies the current array to a new one for the operation. While fordoesn't care of that part. - Interviewer asked me 2 scenario based question in one interview:
- for (int i = 1; i <= 5; i++)
- {
- i = i + i;
- }
Yes this will work.- int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };
- foreach (int i in tempArr)
- {
- i = i + 1;
- }
No comments:
Post a Comment