Home > Software engineering >  How to print numbers in a 2D array in c#?
How to print numbers in a 2D array in c#?

Time:11-23

i have made a 2D array in c#. I want have a method to fill in some numbers and a method to print it. But this doesnt work. Since it is for school. The static void main cant be changed. Can anyone help me? the if statement is true and will say invalid number of arguments here is some code:

static void Main(string[] args)
{
    if (args.Length != 2)
    {
        Console.WriteLine("invalid number of arguments!");
        Console.WriteLine("usage: assignment[1-3] <nr of rows> <nr of columns>");
        return;
    }
    int numberOfRows = int.Parse(args[0]);
    int numberOfColumns = int.Parse(args[1]);
    Program myProgram = new Program();
    myProgram.Start(numberOfRows, numberOfColumns);
}

void Start(int numberOfRows, int numberOfColumns)
{
    int[,] matrix = new int[numberOfRows, numberOfColumns];
    InitMatrix2D(matrix);
    DisplayMatrix(matrix);
}

void InitMatrix2D(int[,] matrix)
{
    int numberPlusOne = 1;
    for (int rows = 0; rows < matrix.GetLength(0); rows  )
    {
        for (int columns = 0; columns < matrix.GetLength(1); columns  )
        {
            matrix[rows, columns] = numberPlusOne  ; // telkens vullen met  1
        }
    }
}

void DisplayMatrix(int[,] matrix)
{

    for (int rows = 0; rows < matrix.GetLength(0); rows  )
    {
        for (int columns = 0; columns < matrix.GetLength(1); columns  )
        {
            Console.Write($"{matrix[rows, columns]}");
        }
    }
}

The if statement is true.

CodePudding user response:

It may not be obvious, but the array of strings passed to Main(string[] args)args — are the arguments passed to the program on the command line, aptly called command line arguments. If you start a C# program named, say, myprog from a Console window with myprog 1 2 3, the operating system and .net runtime see to it that args will have (typically) four elements, namely "myprog", "1", "2" and "3". Perhaps the first one is missing and it's only "1", "2" and "3"; that seems to be the case when I try it on Windows 10 and .net 5.0.

You have probably never started your (or maybe any) program from the command line, hence your confusion.

In order to start a custom program which is not in the program search path from the Console, you need to know where it is because you either cd there or type the entire path name. The program may not be easy to find if you work with an IDE like Visual Studio.1

But Visual Studio allows you to pass arguments to the program via the project's properties dialog. Right-click the project, click Properties at the bottom, choose "Debug" on the left and enter two numbers in the "Application arguments" text box. Then hit F5 if you have a Debug build configuration active.

As an aside:

  • It is customary to return from Main with a non-zero value if the program encounters an error. That return value is used as the exit status of the program, which can be inspected by the caller. The wrong number of arguments is a very basic error condition that should be diagnosable: A script may choose not to continue when a critical step in a processing chain failed. It would be better to declare Main to return int. That way you can return non-zero when an error is encountered. Since you cannot change Main, this is perhaps a note to your teacher (who will likely answer that he doesn't want to complicate matters ;-) ).
  • It is customary to make error output on standard error, not on standard out. The reason is that a caller may parse the standard output (perhaps output from a chain of programs, not only yours!) and would be confused by unexpected text in the standard output. It would be better to write Console.Error.WriteLine("invalid number of arguments!");.

1 You can right-click the editor tab of a source file in Visual Studio and click "open containing folder"; somewhere below that project folder is an exe file, simply search *.exe in the explorer that opened. Right-click the entry with your exe and choose "open file location", then shift-right-click that folder and choose "open cmd window here", or the powershell equivalent.

Whew.

Now, if your program is named program.exe, type program 5 7 or whatever values you desire, and it should work.

CodePudding user response:

Here are two different ways to display a matrix

1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
16,17,18,19,20
21,22,23,24,25
26,27,28,29,30
31,32,33,34,35

|       1        2        3        4        5|
|       6        7        8        9       10|
|      11       12       13       14       15|
|      16       17       18       19       20|
|      21       22       23       24       25|
|      26       27       28       29       30|
|      31       32       33       34       35|

The first way is like a CSV file, with comma-separated values for each row. It is still human-readable but primarily targeted toward file operations.

The second way is arranged in a table/grid which far more human-readable, but less readable by computers.

The code to generate the above two styles is declared using extension methods, DisplayDelimited() and DisplayTable()

public static class DisplayExtensions
{
    public static string DisplayDelimited<T>(this T[,] matrix, string columnSeparator = ",")
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < matrix.GetLength(0); i  )
        {
            for (int j = 0; j < matrix.GetLength(1); j  )
            {
                if (j > 0)
                {
                    sb.Append(columnSeparator);
                }
                sb.Append(matrix[i, j]);
            }
            sb.AppendLine();
        }
        return sb.ToString();
    }

    public static string DisplayTable<T>(this T[,] matrix, int columnWidth = 8, string bracketSymbol  = "|")
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < matrix.GetLength(0); i  )
        {
            sb.Append(bracketSymbol);
            for (int j = 0; j < matrix.GetLength(1); j  )
            {
                if (j > 0)
                {
                    sb.Append(" ");
                }
                sb.Append(matrix[i, j].ToString().PadLeft(columnWidth));
            }
            sb.AppendLine(bracketSymbol);
        }
        return sb.ToString();
    }
}

class Program
{
    static void Main(string[] args)
    {
        int value = 0;
        int[,] matrix = new int[7, 5];
        for (int i = 0; i < 7; i  )
        {
            for (int j = 0; j < 5; j  )
            {
                matrix[i, j] =   value;
            }
        }

        Console.WriteLine(matrix.DisplayDelimited());

        Console.WriteLine(matrix.DisplayTable());
    }
}
  • Related