Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Way to input entire 2D array at once in C#?

I wrote this code for a 1D array:

int[] arr= new int[9];
arr=Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse)

It takes my whole input at once and converts it as an array besides removing spaces. Where input is 1 2 3 4 5 6 7 8 9.

This same concept was tried for 2D arrays but still can’t match. Here is my code,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int[,] arr = new int[3, 3];

for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
    {
        arr[i, j] =Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
    }
}

My input is:

1 2 3
4 5 6
7 8 9

What is the solution? How can I input the entire 2D array at once in C#?

>Solution :

You should call Console.ReadLine for every line and then put in the values:

int[,] arr = new int[3, 3];

for (int i = 0; i < 3; i++)
{
    int[] temp = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);

    for (int j = 0; j < 3; j++)
    {
        arr[i, j] = temp[j];
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading