Making an array of random ints

You are never assigning the values inside the test2 array. You have declared it but all the values will be 0. Here’s how you could assign a random integer in the specified interval for each element of the array:

int Min = 0;
int Max = 20;

// this declares an integer array with 5 elements
// and initializes all of them to their default value
// which is zero
int[] test2 = new int[5]; 

Random randNum = new Random();
for (int i = 0; i < test2.Length; i++)
{
    test2[i] = randNum.Next(Min, Max);
}

alternatively you could use LINQ:

int Min = 0;
int Max = 20;
Random randNum = new Random();
int[] test2 = Enumerable
    .Repeat(0, 5)
    .Select(i => randNum.Next(Min, Max))
    .ToArray();

Leave a Comment