How would I put a range of numbers in an array?

928 Views Asked by At

First post. I am trying to put a large range of numbers into an array (-1000 to 1000) and then do an exponential search. I have very little experience with c# and getting stuck on how to put such a large range into an array. I've been trying a for loop but got stuck.

int[] rangeArray = new int [2000];
            for(int x = -1000; x < 1000; ++x)
            {
                rangeArray[x + 1000] = x;
            }
1

There are 1 best solutions below

0
On

You can use Enumerable.Range for this:

int[] numbers = Enumerable.Range(-1000, 2001).ToArray();

The first variable is "start" and the second is "count".

The result is that the first item's value is -1000 and the last item's value is 1000.

Alternative method using a loop:

int[] values = new int[2001];

for (int i = -1000; i <= 1000; ++i)
{
    values[i+1000] = i; // since arrays start at 0, we have to add 1000 to ensure the first item gets puts in 0, and the last in 2000.
}