Difference between FOR LOOP and FOREACH LOOP? | SoloLearn: Learn to code for FREE!

+8

Difference between FOR LOOP and FOREACH LOOP?

7/1/2017 1:02:27 AM

Biel Blue

2 Answers

New Answer

+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.

+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