Hello,
What is difference between For and foreach loop??
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sam HobbsPosted May 12, 2011, 4:51 PM
Also, you can think of a for loop as a while loop with a couple of extra lines. For example:
for (int i=0; i< 9; ++i)
;
Is the same as or nearly the same as:
int i = 0;
while (i<9)
++i;
Suthish NairPosted May 12, 2011, 2:14 PM
http://www.codeproject.com/KB/cs/foreach.aspx
Andrew FensterPosted May 12, 2011, 10:59 AM
In addition, foreach is only good for looping through items in a collection. The for command is used for other things as well. For example, if you just want to perform an action a specific number of times you would do this:
for (int x = 0; x < 10; x++)
For also allows a lot more control. Here I'm looping from 0 to somevalue in 5 unit increments:
for (int x = 0; x < someValue; x += 5)
Here I'm looping from 300 until x < the value of Foo( ). Foo( ) is recalculated after each loop. I reduce x by .3 after each loop. You can't do that kind of thing with a foreach loop. A foreach loop is meant to perform some action for each item in a collection.
for(int x = 300; x < Foo( ); x *= .7)
As far as looping through each item in a collection, you can use for or foreach. Either one is fine.
Dorababu MekaPosted May 12, 2011, 3:44 AM
for is simple combination of simple loop combined with direct access to items in collection. There is no kind of blocking while this loop is going.