Difference between FOR LOOP and FOREACH LOOP? | Sololearn: Learn to code for FREE!
+ 8

Difference between FOR LOOP and FOREACH LOOP?

1st Jul 2017, 1:02 AM
Biel Blue
Biel Blue - avatar
2 Answers
+ 4
foreach is used to iterate over each element of a given set or list (anything implementing IEnumerable) in a predefined manner. You can't influence the exact order (other than skipping entries or canceling the whole loop), as that's determined by the container. while the for loop is just as any other loop where it contains three steps initialization condition and increment/decrement.
1st Jul 2017, 1:14 AM
Nirmal Kumar Bhakat
Nirmal Kumar Bhakat - avatar
+ 3
int[] anArr = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 }; int sum = 0; for (int i = 0; i < anArr.Length; i++) sum = sum + anArr[i]; //Here u need to give the length of the array as condition int[] anArr = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 }; int sum = 0; foreach (int anInt in anArr) sum = sum + anInt; //This loop iterates for each element in the array
1st Jul 2017, 1:16 AM
Nirmal Kumar Bhakat
Nirmal Kumar Bhakat - avatar