This is very basic question asked in many interviews:
- 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 ;
- }
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;
- 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;
- }
The above code will work?
Yes this will work.
- int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };
- foreach (int i in tempArr)
- {
- i = i + 1;
- }
Above code will work?
This code will not compile. I have pasted screenshot of error.