1

Thinking like a simple array:

Console.WriteLine("Number: ");
int x = Convert.ToInt32(Console.ReadLine());

string[] strA = new string[x];

strA[0] = "Hello";
strA[1] = "World";    

for(int i = 0;i < x;i++)
{
    Console.WriteLine(strA[i]);
}

Now, how can I do it with a double array?

I've already tried this:

Console.WriteLine("Number 1: ");
int x = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Number 2: ");
int y = Convert.ToInt32(Console.ReadLine());

// Got an error, right way string[x][];
// But how can I define the second array?
string[][] strA = new string[x][y]; 

strA[0][0] = "Hello";
strA[0][1] = "World";
strA[1][0] = "Thanks";
strA[1][1] = "Guys"; 

for(int i = 0;i < x;i++)
{
    for(int j = 0;i < y;i++)
    {
        // How can I see the items?
        Console.WriteLine(strA[i][j]); 
    }
}

If's there's a simpler way of doing this, i'll be happy to learn it.

It's only for knowledge, I'm studying double array for the first time, so have patience please :)

Here's my example: https://dotnetfiddle.net/PQblXH

LeoHenrique
  • 229
  • 5
  • 16
  • 2
    What's wrong with what you've written? – NibblyPig Mar 22 '19 at 13:45
  • Double array ? Like an array of double or a 2Dimention array ? https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays – xdtTransform Mar 22 '19 at 13:45
  • Minor misunderstanding on your part, these are not double arrays they're called two dimensional arrays (there one, two, three ... n dimensional arrays). A double array would be an array of doubles – MindSwipe Mar 22 '19 at 13:46
  • @xdtTransform if you look at the code you can see he means two dimensional arrays and not double arrays – MindSwipe Mar 22 '19 at 13:47
  • I got this error when I define value to array (strA[0][1] ...), sorry i forgot to post that [System.NullReferenceException: Object reference not set to an instance of an object.] at Program.Main() – LeoHenrique Mar 22 '19 at 13:49
  • @MindSwipe, Retorical question to show the missleading title. And the documentation linked is all about multi dim array. – xdtTransform Mar 22 '19 at 13:49
  • @MindSwipe, thanks, I didnt know that had this name – LeoHenrique Mar 22 '19 at 13:50
  • 1
    @MindSwipe it's not a two dimensional array, it's a jagged array. A two dimensional array would be `string[,]` – Magnetron Mar 22 '19 at 13:50
  • 1
    @LeoHenrique That pertinent information should be in your question. –  Mar 22 '19 at 13:51
  • You should have error using 0 and negative number and number that exceeds int max – xdtTransform Mar 22 '19 at 13:53
  • X and Y are Size not index. How do you mentaly picture an array where one dim is 0 and the other is 1? – xdtTransform Mar 22 '19 at 13:54
  • X is the size the array containing the other array of size Y. If X is 0 there is no array in the 1rst dimention. How could this nothing has a size of 1? – xdtTransform Mar 22 '19 at 13:56
  • @xdtTransform, yeah its I size, Im trying to define the size, for after, see the results, one by one – LeoHenrique Mar 22 '19 at 13:57
  • Your fiddle code looks unrelated to your question.. You should take 5 minute and write in 3-4 simple sentences what you are trying to achieve. It will translate into code quite simply. – xdtTransform Mar 22 '19 at 14:05
  • Possible duplicate of [What is a jagged array?](https://stackoverflow.com/questions/2576759/what-is-a-jagged-array) – fhcimolin Mar 22 '19 at 14:43

4 Answers4

6

You are working with jagged array (i.e. array of array string[][]), not 2D one (which is string[,])

If you want to hardcode:

  string[][] strA = new string[][] { // array of array
    new string[] {"Hello", "World"}, // 1st line 
    new string[] {"Thanks", "Guys"}, // 2nd line
  };

in case you want to provide x and y:

  string[][] strA = Enumerable
    .Range(0, y)                   // y lines
    .Select(line => new string[x]) // each line - array of x items
    .ToArray(); 

Finally, if we want to initialize strA without Linq but good all for loop (unlike 2d array, jagged array can contain inner arrays of different lengths):

  // strA is array of size "y" os string arrays (i.e. we have "y" lines)
  string[][] strA = new string[y][];

  // each array within strA
  for (int i = 0; i < y; ++i)
    strA[i] = new string[x]; // is an array of size "x" (each line of "x" items)

Edit: Let's print out jagged array line after line:

Good old for loops

  for (int i = 0; i < strA.Length; ++i) {
    Console.WriteLine();

    // please, note that each line can have its own length
    string[] line = strA[i];

    for (int j = 0; j < line.Length; ++j) {
      Console.Write(line[j]); // or strA[i][j]
      Console.Write(' ');     // delimiter, let it be space
    }
  } 

Compact code:

  Console.Write(string.Join(Environment.newLine, strA
    .Select(line => string.Join(" ", line))));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • ok, but to define the items with an console.readline for example, how can i do? string[][] strA = new string[][]; .... – LeoHenrique Mar 22 '19 at 13:58
  • @LeoHenrique: since *jagged arra*y can contain arrays of *different lengths*, e.g. `new string[][] {new string[] {"a", "b", "c"}, new string[] {"p", "q"}};` we have to initialize it with a help of *loop* (if we don't want *Linq*) – Dmitry Bychenko Mar 22 '19 at 14:07
  • @LeoHenrique: 1st index - "line", 2nd index - column; `strA[0][0] = "Hello"; strA[0][1] = "World";` let's print out the 1st line now: `Console.Write(string.Join(" ", strA[0]));` – Dmitry Bychenko Mar 22 '19 at 14:10
  • for your last example: new string[][] {new string[] {"a", "b", "c"}, new string[] {"p", "q"}}; (its hard to understand for me) how i show this, like console.writeline(strA[...]), I want to see "a" and after "p" – LeoHenrique Mar 22 '19 at 14:11
  • @LeoHenrique: if you want to see `"a"` after `"p"` put it as `new string[][] {new string[] {"p", "a"}, new string[] {"q", "b"}, nes string[] {"c"}};` and you'll have lines `"p, a"`, `"q", "b"`, `"c"` – Dmitry Bychenko Mar 22 '19 at 14:18
  • ok, one of my doubt solved, so each line I have a lenght, but to choose the 'column'?, i thinking this line 1 column 1: "a" line 2 column 1: "b", line 1 column 2: "p". Is my thought right? – LeoHenrique Mar 22 '19 at 14:24
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/190511/discussion-between-dmitry-bychenko-and-leohenrique). – Dmitry Bychenko Mar 22 '19 at 14:26
3

You're using a jagged array instead of a multidimensional one. Simply use [,] instead of [][]. You can then use it with new string[x, y].

Biesi
  • 800
  • 9
  • 17
  • Thanks for your help, but I want to learn how to do with this 2, I started with jagged array, so when I understand that, I'll try the multidimensional. But thanks so much :) – LeoHenrique Mar 22 '19 at 14:27
1

First you need to clarify thing in your head before writing code.
I will recommend writing in simple phrase what you want to do. The code in your fiddle go into every direction. I will address the code in the fiddle and not your questionas you have typo error and other issue that where not present in the fiddle while the fiddle has error that the question do not have.

To simplify the problem lets use clear understandable names. The 2d array will be an table, with rows and columns.

//  1/. Ask for 2table dim sizes.
Console.WriteLine("Enter number of rows:");
var x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number of columns:");
var y = int.Parse(Console.ReadLine());

var table = new string[x, y];

You need to to declare your table before knowing its size.

// 2/. Fill the board
for (int row = 0; row < table.GetLength(0); row++)
{
    for (int col = 0; col < table.GetLength(1); col++)
    {
        Console.WriteLine($"Enter the value of the cell [{row},{col}]");
        table[row, col] = Console.ReadLine();
    }
}

table.GetLength(0) is equivalent to X, and table.GetLength(1) is equivalent to Y, and can be replace.

// 3/. Display the Table 
Console.Write("\n");
for (int row = 0; row < table.GetLength(0); row++)
{
    for (int col = 0; col < table.GetLength(1); col++)
    {
        Console.Write(table[row, col]);
    }
    Console.Write("\n");
}

For a 3x3 table with 00X, 0X0, X00 as inputs the result is

00X
0X0
X00

It works. You separate each cell when we display by simply adding a comma or a space. Fiddle

And for Jagged Array:

//  1/. Ask for 2table dim sizes.
Console.WriteLine("Enter number of rows:");
var x = int.Parse(Console.ReadLine());

var table = new string[x][];

// 2/. Fill the board
for (int row = 0; row < table.GetLength(0); row++)
{
    Console.WriteLine($"Enter of the line n°{row}");
    var lineSize = int.Parse(Console.ReadLine());
    table[row] = new string[lineSize];
    for (int col = 0; col < table[row].Length; col++)
    {
        Console.WriteLine($"Enter the value of the cell [{row},{col}]");
        table[row][col] = Console.ReadLine();
    }
    Console.Write("\n");
}

// 3/. Display the Table 
Console.Write("\n");
for (int row = 0; row < table.Length; row++)
{
    for (int col = 0; col < table[row].Length; col++)
    {
        Console.Write(table[row][col]);
    }
    Console.Write("\n");
}
xdtTransform
  • 1,986
  • 14
  • 34
0

Wrong variable in use:

for(int j = 0;i < y;i++) <- Should be j
{
    // How can I see the items?
    Console.WriteLine(strA[i][j]); 
}
Seiche
  • 3
  • 4