nick folly nick folly - 1 month ago 5
C# Question

i wrote a function to print all elements in array

i wrote a function to print array elements but when i call it in the main it doesn't print anything

public static string PrintArray (int [,] arr)
{
string output = "";
for (int i = 0; i<arr.GetLength(0);i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
output += arr[i,j];
}
output = output.Substring(0, output.Length)+"/n";
}
return output;
}

PrintArray(MArry); //calling the function as it is in the main

Answer

Something like this:

public static string PrintArray (int [,] arr)
{
    // validate public methods' arguments
    if (null == arr)
        return ""; // or throw exception

    // When builing string in loop(s) use StringBuilder instead of +=
    StringBuilder output = new StringBuilder();

    for (int i = 0; i < arr.GetLength(0); i++)
    {
        for (int j = 0; j < arr.GetLength(1); j++)
        {
            if (j > 0)
                output.Append(", "); // do not forget about delimiters   

            output.Append(arr[i,j]);
        }

        // do not forget about delimiters (\n, please, notice \ instead of /)
        // Environment.NewLine is a better choice than \n
        if (i > 0)
            output.Append("\n");
    }

    return output.ToString();
}

Having the string formed, do not forget to print it out

Console.Write(PrintArray(MArry));
Comments