Search code examples
c#arraysmultidimensional-arraymethods

Calling a method to fill a 2d array in C#


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;
    }
}

}


Solution

  • 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 on Random for more details