Hello,
What is difference between For and foreach loop??
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Dorababu MekaRank #457 · 5.5K reputationPosted May 11, 2011, 11:44 PM EDT
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.
Andrew FensterRank #983 · 2K reputationPosted May 12, 2011, 6:59 AM EDT
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.
Suthish NairRank #92 · 22.8K reputationPosted May 12, 2011, 10:14 AM EDT
http://www.codeproject.com/KB/cs/foreach.aspx
Sam HobbsRank #107 · 20.5K reputationPosted May 12, 2011, 12:51 PM EDT
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;