Ok the output of this code is
Element[0] = 100
Element[0] = 101
Element[0] = 102
Element[0] = 103
Element[0] = 104
Element[0] = 105
Element[0] = 106
Element[0] = 107
Element[0] = 108
Element[9] = 109
its supposed to be
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
The code is below. I fixxed the issue, but this code snippet comes straight from a tutorial website.
What I don't know is why doesn't the foreach() loop add the Element numbers in? I had to change
the i = 0; to i = j - 100; in order to make it output properly. Is anyone else getting the zero's
on their output? Again I am using Visual Studio Express 2012. Why doesn't their code snippet work? What's
wrong with that foreach loop to cause i not to increment and display properly?
foreach statement to iterate through an array.
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers */
/* initialize elements of array n */
for ( int i = 0; i < 10; i++ )
{
n[i] = i + 100;
}
/* output each array element's value */
foreach (int j in n )
{
int i = 0; //<--- I changed this to int i = j - 100; and the code works properly.
Console.WriteLine("Element[{0}] = {1}", i, j);
i++;
}
Console.ReadKey();
}
}
}