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.
- 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 ;
- }
- Using for loop we can iterate a collection 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 for doesn't care of that part.
The above code will work?- for (int i = 1; i <= 5; i++)
- {
- i = i + i;
- }
Yes this will work.
Above code will work?- int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };
- foreach (int i in tempArr)
- {
- i = i + 1;
- }
This code will not compile. I have pasted screenshot of error.

Learn more here: The for Vs foreach Loop In C#

Dinesh KumarPosted Dec 10, 2021, 7:00 AM
This article is very nice
Sudhir DehadePosted Apr 18, 2018, 1:36 PM
This article is very nice. I have one question ...... 3.In variable declaration, foreach has five variable declarations....... Can you please elaborate this statement..?