1

I am writing C# program for a matrix.when I enter matrix inputs from console, each element is coming in the separate row.But, I want to read row elements in a single line.

This is my code

            Console.WriteLine("Enter the matrix");
            int n= Convert.ToInt32(Console.ReadLine());
            int[ , ] matrix=new int[n,n];
            for(int i=0; i<n; i++){
                for(int j=0; j<n; j++){
                    matrix[i,j]=Convert.ToInt32(Console.ReadLine());
                   // Console.Write("\t");
                }

            }

present I am getting like

1

2

3

4

But, I want like

1 2

3 4

Help me.

Tarabass
  • 3,132
  • 2
  • 17
  • 35
Nagarjuna Reddy
  • 4,083
  • 14
  • 41
  • 85

4 Answers4

0

You can enter the entire line and do the following:

for(int i=0; i<n; i++){
    var input = Console.ReadLine().Split(' ').Select(t => int.Parse(t)).ToArray();
    for (int j = 0 ; j < n ; j++){
          matrix[i, j] = input[j];

    }

}
Maor Veitsman
  • 1,544
  • 9
  • 21
0
            Console.WriteLine("Enter the matrix");
            int n= Convert.ToInt32(Console.ReadLine());
            int[ , ] matrix=new int[n,n];
            for(int i=0; i<n; i++){
            string line = Console.ReadLine();
            string[] elements = line.Split(' ');

                for(int j=0; j<n || j < elements.Length; j++){
                    matrix[i,j]=Convert.ToInt32(elements[j]);
                }    
            }
0

If you want to read one row in one line, you can ask user to enter space-separated values like 1 2, 3 4 and read like this

Console.WriteLine("Enter the matrix size");
int n = Convert.ToInt32(Console.ReadLine());
//add size and other validation if required
int[,] matrix = new int[n, n];
Console.WriteLine("Enter your values separated by space.");
for (int i = 0; i < n; i++)
{
    var values = (Console.ReadLine().Split(' '));
    for (int j = 0; j < n; j++)
    {
        matrix[i, j] = int.Parse(values[j]);
    }
}

//to write 
for (int i = 0; i < n; i++)
{
    for (int j = 0; j < n; j++)
    {
        Console.Write(matrix[i, j] + " ");
    }
    Console.WriteLine();
}
Arghya C
  • 9,805
  • 2
  • 47
  • 66
0

Please look same question

In your situation :

for(int i = 0; i < n; i++){
      for(int j = 0; j < n; j + 2){
        string input = Console.ReadLine();
        string[] split = input.Split(' ');
        int firstNumber = Int32.Parse(split[0]);
        int secondNumber = Int32.Parse(split[1]);
        matrix[i,j] = firstNumber ;
        matrix[i,(j+1)] = secondNumber ;
       }
   }
Community
  • 1
  • 1
Tarık Özgün Güner
  • 1,051
  • 10
  • 10