Home > Mobile >  how to insert a new value in a two dimensional array?
how to insert a new value in a two dimensional array?

Time:11-15

I have this matrix 10x10 filled with random chars. My problem I can't figure out how to insert a string "HOUSE" in to the table.


`Random rchar = new Random();
string word = "HOUSE";
char[] wordChars = word.ToCharArray();
char[,] arr = new char[10, 10];

//Size of Rows and Cols
var rowLength = arr.GetLength(0);
var colLength = arr.GetLength(1);

for (int x = 0; x < rowLength; x  )
{
    for (int y = 0; y < colLength; y  )
    {
        arr[0, y] = chars[1];
        arr[x, y] = (char)(rchar.Next(65, 91));
        Console.Write(arr[x, y]   " ");
    }
    Console.WriteLine();
}`

I was trzing to place a new value with the SetValue property but it dosent work for me couse i have two deminsional array

CodePudding user response:

Just set to your arr using two dimentional indices like [1,1] or [x,y]

Example:

    public static void Main()
    {
        Random rchar = new Random();
        char[,] arr = new char[10, 10];

        //Size of Rows and Cols
        var rowLength = arr.GetLength(0);
        var colLength = arr.GetLength(1);

        for (int x = 0; x < rowLength; x  )
        {
          for (int y = 0; y < colLength; y  )
          {
            arr[x,y] = (char)(rchar.Next(65, 91));
            Console.Write(arr[x, y]   " ");
          }
          Console.WriteLine();
       }
    }

CodePudding user response:

Try running this piece of code, I think it covers your question of setting values in a multidimensional array. Also I see a "chars[1]" in your code, this variable does not exist, did you mean to get the random char here? You might want to look up how to get a random char and put it in that spot.

char[,] arr = new char[10, 10];

arr[0, 0] = 'a';
arr[0, 1] = 'b';
arr[0, 2] = 'c';

arr[1, 0] = 'd';
arr[1, 1] = 'e';
arr[1, 2] = 'f';

for (int i = 0; i < 3; i  )
{
    Console.WriteLine(arr[0, i]);
}

for (int i = 0; i < 3; i  )
{
    Console.WriteLine(arr[1, i]);   
}
  •  Tags:  
  • c#
  • Related