I was doing some past exam questions as a way of studying for an exam next month. One of the questions that I could not do was this: "Write a procedure that returns a two dimensional square array of size n x n, initialised with random real numbers between -100 & 200".

I have two problems with this question. Firstly, how can I manipulate my loop to include negative values (i.e. 'real' as opposed to 'int')? Secondly, how can I make it any square array, like a 2 x 2 or 17 x 17, for example? Any help would be very much appreciated.

Info here: http://msdn.microsoft.com/en-us/library/2yd9wwz4(v=vs.71).aspx

You define it "square" by giving it the same size on both sides when you declare your array.

I whipped this up real quick. There are probably better ways to do it.

int N = 3;
Random rnd = new Random();
double min = -100.0;
double max = 200.0;

double[,] array = new double[N,N]; /*a single ',' in the [] means 2 dimensions*/
for(int i = 0; i<N; i++)
{
    for(int j = 0; j<N; j++)
    {
        array[i, j] = rnd.NextDouble() * (Math.Abs(max) + Math.Abs(min)) - Math.Abs(min); //this is done so there are negative values between your range
    }
}

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

Line 11 doesn't work if both are positive values. For example, if the range was 1.0 to 3.0, you'd get 3.0+1.0 = 4,0, so values from 0.0 to 4.0, then you'd subtract one from that giving values from -1.0 to 3.0. There is no need to use Math.Abs

array[i, j] = rnd.NextDouble() * (max-min)+min;

So for my example you'd get (3.0-1.0) = 2.0 (ranges from 0.0 to 2.0) + 1.0 (ranges from 1.0 to 3.0, the goal). In the example given you'd get (200.0 - (-100.0)) = 300.0 (ranges from 0.0 to 300.00) + (-100.0) (ranges from -100.0 to 200.0, the goal).

With mine, you can even reverse the min/max values and still get the right answer (For example, using 1.0 and 3.0 again (with 1.0 in place of max) we'd get (1.0 - 3.0) = (-2.0) so range from -2.0 to 0.0, add in min (which is 3.0 this time) and you get 1.0 to 3.0, the goal).

Thanks a million guys. I understand everything now except for line 11. Why is there multiplication and addition etc? Also, is there anyway to format the output as a square? It returns nxn but linearly. Is this right?

NextDouble returns a value from 0.0 to (less than) 1.0. The multiplication and addition is to get the value into the range you want.

Yes, you can output it as a square, change lines 15-21 to

for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
        Console.Write("{0} ", array[i, j]);
    }
    Console.WriteLine();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.