Click here to Skip to main content
15,905,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i'm trying to populate a 2d array in c# using random values .. i've stucked...here is my code
C#
Random random = new Random();
int[ , ] numbers = new int[ no_of_rows , no_of_columns ];

 int row_value = 0;
 int column_value = 0;

// populating 2D Array

for (int m = 0; m < 5 ; m++)
{
    for (int n = 0; n < 5 ; n++)
    {
        row_value = random.Next(0,25);
        column_value = random.Next(0, 25);
        numbers[m,n] = [row_value,column_value];
    }
}
Posted
Updated 20-Sep-14 18:28pm
v2

C#
// random integer returned can include this value
private const int randMinimum = 0;

// note that random integer returned maximum value will be 
// one less than the value specified: i.e., in this case, #25
private const int randMaximum = 26;

private const int no_of_rows = 5;
private const int no_of_columns = 5;

// fancy way of getting more randomness than you will probably ever need
private Random random = new Random(Guid.NewGuid().GetHashCode());

private int[ , ] numbers = new int[ no_of_rows , no_of_columns ];

// populating 2D Array        
for (int row = 0; row < no_of_rows; row++)
{
    for (int column = 0; column < no_of_columns; column++)
    {
        numbers[row, column] = random.Next(randMinimum, randMaximum);
    }
}
 
Share this answer
 
v2
Comments
ChauhanAjay 21-Sep-14 3:41am    
I like your answer also. +5 for you.
Try the below code

C#
Random random = new Random();
int[ , ] numbers = new int[5,5];
//populating 2D Array
for (int m = 0; m < 5 ; m++)
{
    for (int n = 0; n < 5 ; n++)
    {
        numbers[m,n] = random.Next(0, 25);
    }
}


Hope it helps
 
Share this answer
 
Comments
ChauhanAjay 21-Sep-14 1:48am    
Why is the answer downvoted?
Can anybody tell me what is wrong in the answer?
Ammar Shaukat 21-Sep-14 3:23am    
thanks.. it is working...
BillWoodruff 21-Sep-14 3:33am    
+5 this is a working answer, and it should not have been down-voted !

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900