0

I am making a array filled with random numbers in c# but I can't get it to work.

        int[,] array = new int[10, 5];
        int x, y;
        x = 0;
        y = 0;

        while (y <= 5)
        {
            Random r = new Random();
            int rand = r.Next(-50, 50);
            array[x, y] = rand;

            if (x == 10)
            {
                x = 0;
                y++;
            }
            x++;

        }
1
  • 1
    Take Random r = new Random(); out of the while loop. Otherwise, you're reseeding with the same seed every time! Commented Mar 6, 2014 at 6:12

5 Answers 5

4

Use nested for loops, it is much easier:

Random rnd = new Random();
for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 5; j++)
    {
        array[i, j] = rnd.Next(-50, 50);
    }
}

Your while loop is not readable but it's correct,except you should change while (y <= 5) to while (y < 5) otherwise you will get an IndexOutOfRangeException. And you should define your Random instance outside of the loop.

Sign up to request clarification or add additional context in comments.

Comments

0
int[,] array = new int[10, 5];
int x = 0, y = 0;

Random r = new Random();
while (y < 5)
{    
    int rand = r.Next(-50, 50);
    array [x, y] = rand;

    x++;
    if (x == 10)
    {
        x = 0;
        y++;
    }
}

Comments

0

Try this:

int[,] array = new int[10, 5];


        Random rnd = new Random();

        for (int row = 0; row < 10; row++)
        {
            for (int col = 0; col < 5; col++)
            {
                array[row, col] = rnd.Next(-50, 50);
            }
        }

Comments

0

you need to change yours if or array declaration to

 int[,] array = new int[11, 6];

also there is other problem, you need to create random before while

        Random r = new Random();

        while (y <= 5)
        {

to print out the values you can use for

        for (int i = 0; i < array.GetLength(0); i++)
        {
            for (int j = 0; j < array.GetLength(1); j++)
                Console.WriteLine(array[i, j]);
        }

Comments

0
int[,] array = new int[10, 5];
        int x, y;
        x = 0;
        y = 0;

        while (y < 5)
        {
            Random r = new Random();
            int rand = r.Next(-50, 50);
            array[x, y] = rand;

            if (x == 9)
            {
                x = 0;
                y++;
            }
            x++;

        }

Let's see if this works.

Comments

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.