So I tried googling but I can't find any information that answers my question.
Basically I have an array that consists out {1,2,3,4,5,6,7,8,9,10}. I have a for loop and a foreach loop that as far as i know do the same thing (print only the numbers divisible by 2). The for loop works fine - it prints 2,4,6,8 and 10. The foreach loop also seems to print the correct integers, but for some reason it throws a IndexOutOfRangeExeption. Why does the for loop work completly fine with no errors, but the foreach loop prints the correct integers but still throws an error?
Here is the code:
int[] tenNums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Console.WriteLine(tenNums.Length);
for (int i = 0; i < tenNums.Length; i++)
{
if (tenNums[i] % 2 == 0)
{
Console.WriteLine(tenNums[i]);
}
}
foreach (int i in tenNums)
{
if (tenNums[i] % 2 == 0) // <== Error happens on this line
{
Console.WriteLine(tenNums[i]);
}
}
Console.ReadKey();