42

What i try to to, is generate an array of random int values, where the random values are taken between a min and a max.

So far i came up with this code:

int Min = 0;
int Max = 20;

int[] test2 = new int[5];
Random randNum = new Random();
foreach (int value in test2)
{
    randNum.Next(Min, Max);
}

But its not fully working yet. I think i might be missing just 1 line or something. Can anyone help me out pushing me in the right direction ?

1
  • 2
    You're not actually assigning a value to your array each iteration. Commented Jan 15, 2012 at 14:03

2 Answers 2

76

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();
Sign up to request clarification or add additional context in comments.

1 Comment

that first one gave me even more errors, and so far my knowledge of c# just is about 2 weeks back hehe. the second one works like a charm. thanx for that
0

You need to assign the random.next result to the currrent index of your array within the loop

3 Comments

You can't add to an array, that's a list.. and if you did it in a foreach loop, the collection would be modified while iterating.
Sorry, but it's still the wrong answer and a bad one: using foreach is to access an array's elements, you can't populate them that way
Ahh I totally ignored the foreach loop in the original question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.