For and foreach
Can any on explain what is difference between for and foreach
2 Answers
Know the answer? Post it. Somebody with the same question will find it here.
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
Sanjeeb LenkaRank #301 · 8.3K reputationPosted Dec 2, 2013, 8:51 PM EST
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 ;
}
Sanjay KumarRank #561 · 4.3K reputationPosted Dec 2, 2013, 8:53 PM EST
http://www.dotnetperls.com/for
http://www.dotnetperls.com/foreach
http://www.codeproject.com/Articles/6759/FOREACH-Vs-FOR-C