int[] numbers = new int[5]; int a = 0; while (a < numbers.Length) { numbers[a] = a; Console.WriteLine(numbers[a]); a++; }

14,694,016 members

See more:

I've been to fill an array with an while loop, output should be 1, 2, 3, 4, 5.

I get systemindex out of range, any ideas how to fix this?

**What I have tried:**

I get systemindex out of range, any ideas how to fix this?

int[] numbers = new int[5]; int a = 0; while (a <= numbers.Length) { numbers[i + 1] = i; Console.WriteLine(numbers[a]); a++; }

Try this:

int[] numbers = new int[5]; int a = 0; while (a < numbers.Length) { numbers[a] = a; Console.WriteLine(numbers[a]); a++; }

v2

Comments

Nice answer. You could save a line by doing this: Console.WriteLine(numbers[a++]);. It's not as clear as your solution but it illustrates the use of the post-increment operator

Was thinking about that too, but too lazy too correct the solution :)

To add to what Rick has said, array indexes in C# run from zero, so a five element array called "a" will have five valid indexes:

But the Length of an array understandably runs from 0 as well: an empty array with no elements has a Length of 0 (and no valid values for its index), and array with one element has a Length of 1 (and just the one valid index: 0), two elements means a Length of 2 (and two indexes: 0 and 1), ... and an array with five elements has a Length of 5 (indexes 0, 1, 2, 3, 4 only).

So when your loop runs from 0 to the Length inclusive:

That's why you nearly always see "<" in loop guard code, and almost never "<="

Make sense?

```
a[0]
a[1]
a[2]
a[3]
a[4]
```

Any other value (i.e. 5 or more, or any negative value at all) is invalid, and you will get an error to tell you that - it's out of range, teh range being 0 to 4 inclusive.But the Length of an array understandably runs from 0 as well: an empty array with no elements has a Length of 0 (and no valid values for its index), and array with one element has a Length of 1 (and just the one valid index: 0), two elements means a Length of 2 (and two indexes: 0 and 1), ... and an array with five elements has a Length of 5 (indexes 0, 1, 2, 3, 4 only).

So when your loop runs from 0 to the Length inclusive:

int a = 0; while (a <= numbers.Length) ...Then the indexes you are trying to use are 0, 1, 2, 3, 4, ... and 5. The final one will always give you an error because there are only five values in a five element array, and five valid indexes: 0, 1, 2, 3, and 4.

That's why you nearly always see "<" in loop guard code, and almost never "<="

Make sense?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900