-1

I am trying to make an app that adds the lines and columns of a matrix. The logic behind the app is that you input in a textbox each line of the matrix on a single line and separate every line with "/". For example: 1 2 3 4/1 2 3 4. Im trying to convert the values from string to int but I keep getting the argument 1 error.

Edit: forgot to add the function for the adding of the rows.

if (decision == 2)
{
    string[] tokens = a.Split('/');
    int[][] tokens1 = new int[][] {
        tokens[0].Split(' ').Select(Int32.Parse).ToArray(),
        tokens[1].Split(' ').Select(Int32.Parse).ToArray()
    };

    row_sum(tokens1, 2);
}

static void row_sum(int[,] arr, int orden)
{
    int i, j, sum = 0;

    // finding the row sum 
    for (i = 0; i < orden; ++i)
    {
        for (j = 0; j < orden; ++j)
        {

            // Add the element 
            sum = sum + arr[i, j];
        }

        // Print the row sum 
        Console.WriteLine("Sum of the row " +
                             i + " = " + sum);

        // Reset the sum 
        sum = 0;
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
R3DVIBES
  • 23
  • 3
  • 2
    A [multidimensional array](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays) is not the same as a [jagged array](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays). In the first part, you use a jagged array (`tokens1`) and in the second one (in the `row_sum` method, variable `arr`), you're using a multidimensional array. You have to use the same in both places, otherwise you'll get that compiler error you're talking about. – Joelius Aug 04 '19 at 11:38

1 Answers1

5

The problem you have is that you're dealing with two different kinds of arrays:

  • tokens1 is a jagged array (int[][]): it is an array of arrays. The child array at tokens1[0] can be a different length to the array at tokens1[1].
  • arr is a 2d array. The dimensions are pre-defined and the length of the second bound never changes based on the first.

See here for more information on 2d arrays vs jagged arrays.

The solution to your problem is to make row_sum accept the same kind of array as you're creating, or create the same kind of array as row_sum accepts.

The easiest option is, perhaps, to make row_sum accept a jagged array:

 static void row_sum(int[][] arr)
 {

    int i, j, sum = 0;

    // finding the row sum 
    for (i = 0; i < arr.Length; ++i)
    {
        for (j = 0; j < arr[i].Length; ++j)
        {

            // Add the element 
            sum = sum + arr[i][j];
        }

        // Print the row sum 
        Console.WriteLine("Sum of the row " +
                             i + " = " + sum);


        // Reset the sum 
        sum = 0;
    }
 }

I took the liberty of removing the length value since it's not required as this information can be obtained from the array itself.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86