Click here to Skip to main content
14,694,016 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
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:

int[] numbers = new int[5];

          int a = 0;

          while (a <= numbers.Length)
          {
              numbers[i + 1] = i;
              Console.WriteLine(numbers[a]);
              a++;
          }
Posted
Updated 25-May-20 5:18am
v2

Try this:
int[] numbers = new int[5];
          int a = 0;

          while (a < numbers.Length)
          {
              numbers[a] = a;
              Console.WriteLine(numbers[a]);
              a++;
          }
   
v2
Comments
George Swan 25-May-20 17:40pm
   
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
RickZeeland 26-May-20 1:20am
   
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:
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?
   
In
numbers[i + 1] = i;

there is a double mistake:
First, you index is not i, it is a
numbers[a + 1] = a;

then, you store values in wrong place because first position in an array is 0
numbers[a] = a+1;
   

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