Calling a method to fill a 2d array in C#
13,290
Your method doesn't fill an array - it creates a new array. (It's also not at all clear what the parameters are meant to be for.)
If you want it to fill an existing array, you should have that as the parameter:
public static void FillArray(int[,] array)
{
Random rnd = new Random();
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
array[i, j] = rnd.Next(1, 15);
}
}
}
Then you can call it from Main
with:
FillArray(myArray);
Notes:
- We don't need to return anything, as the caller has already passed us a reference to the array to be filled
- I've made the method static as it doesn't need to access any state of a
Program
instance - In general, creating a new
Random
instance "on demand" is a bad idea; read my article onRandom
for more details
Author by
Wil
Updated on June 04, 2022Comments
-
Wil almost 2 years
I am a very new programmer, and have been struggling to write a method that can take any 2D array and fill it with random integers from 1 to 15. I believe I managed to build my method correctly, but I can't seem to see how to then call my method to fill the array I made in main. (I would have just filled it in main right out, but I'm trying to practice methods as well.) Here is the code I have so far. I appreciate any help you all are able to give me, thanks!
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Homework2 { class Program { static void Main(string[] args) { int[,] myArray = new int[5,6]; } public int[,] FillArray (int i, int j) { Random rnd = new Random(); int[,] tempArray = new int[,]{}; for (i = 0; i < tempArray.GetLength(0); i++) { for (j = 0; j < tempArray.GetLength(1); j++) { tempArray[i, j] = rnd.Next(1, 15); } } return tempArray; } }
}
-
Dave Zych over 8 yearsI believe the second
for
should be usingarray
, nottempArray
. -
Tim over 8 years@DaveZych - You dare to question the all-knowing Jon Skeet? :)
-
Dave Zych over 8 years@Tim nobody is immune to mistakes :)
-
Tim over 8 years@DaveZych - Yes, I know that. Just couldn't resist the comment, given that it was a Jon Skeet(TM) answer :)
-
Wil over 8 yearsThanks Jon! I appreciate all of the helpful insight as well. Just started on the article you sent me!
-
Idle_Mind over 8 yearsAnother side note...if 15 is to be included in the possible values you want, then use
rnd.Next(1, 16);
. See Random.Next: Return Value - A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue.