0
public override string ToString() {
    string matrixView = "";

    for (int r=0; r<=this.rows; r++) {
        for (int c=0; c<=this.columns; c++) {
                
        }
    }

    return matrixView;
}

Note:
##################################
this.rows = row number
this.columns = column number
this.matrix= 2-dimensional array used as data store
##################################

In this code, I aim to make seem for example 4x4 matrix like:

[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]

Each newline must be started with "[". Values(this.columns times) and spaces(this.columns-1 times) must be printed. Finally, the line must be ended with "]\n" And these operations above must be done this.rowstimes.

I think in this way. But nested loops always make me confuse. So, I tried several times but I couldn't be successful at it. And String.Concat threw NullReferenceExceptionwhen I tried to concaten matrixView with "[", "]\n" and this.matrix[r, c].ToString().

  • Can you please share with us the definition of the `matrix`? – Peter Csala Jun 16 '22 at 09:23
  • matrix is a int[,](two-dminsional int array) field in Matrix struct which is initalized in struct constructor with int rows and int columns. So matrix is int[this.rows, this.columns](two-dimesional array with initalized rows and column numbers). – Ufuk Can İşbildi Jun 16 '22 at 10:22

2 Answers2

1

I think you are looking for something like this:

public override string ToString() {
    // When building string, better use StringBuilder instead of String
    StringBuilder matrixView = new StringBuilder();

    // Note r < matrix.GetLength(0), matrix is zero based [0..this.rows - 1]
    // When printing array, let's query this array - GetLength(0)
    for (int r = 0; r < matrix.GetLength(0); r++) {
        // Starting new row we should add row delimiter 
        if (r > 0)
            matrixView.AppendLine();

        // New line starts from [
        matrixView.Append("["); 

        // Note r < matrix.GetLength(1), matrix is zero based [0..this.rows - 1]
        for (int c = 0; c < matrix.GetLength(1); c++) {
            // Starting new column we should add column delimiter 
            if (c > 0)
                matrixView.Append(' ');

            matrixView.Append(matrix[r, c]);       
        }

        // New line ends with [
        matrixView.Append("]");
    }

    return matrixView.ToString();
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

You could for example do something like:

for (int r=0; r<=this.rows; r++) {
    var s = "[";
    for (int c=0; c<=this.columns; c++) {
        s += myValue.ToString() + " "; 
    }
    s += "]";
    Console.WriteLine(s);
}

But if you numbers are larger than 9 you might want to pad the numbers with spaces. It is not very efficient to do many small concatenations like this. But unless you do this very frequently it will not matter.

JonasH
  • 28,608
  • 2
  • 10
  • 23