for loop used both assigning and accessing values for each loop omly accessing values
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[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 }; foreach (int i in tempArr ) { j = j + i ; }
Nobody really touches on speed in their answers. Which is faster depends on what you're iterating over. Here's a blog comparison that iterates over multiple kinds of objects, such as DataRows and custom objects, also including the performance of the While loop construct and not just the for and foreach constructs: http://cc.davelozinski.com/c-sharp/for-vs-foreach-vs-while
It depends on what you are doing, and what you need. If you are iterating through a collection of items, and do not care about the index values then foreach is more convenient, easier to write and safer: you can't get the number of items wrong. If you need to process every second item in a collection for example, or process them ion the reverse order, then a for loop is the only practical way.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.For more detail, see MSDN : foreach http://msdn.microsoft.com/en-us/library/ttw7t8t6%28v=vs.90%29.aspxand for http://msdn.microsoft.com/en-us/library/ch45axte.aspx
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.
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[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };foreach (int i in tempArr ){j = j + i ;}