Dùng Console.ReadLine() trong lồng vòng lặp để nhập ma trận.
Console.Write("Nhập phần tử ma trận: ");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
arr1[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
Ví dụ
using System;
namespace Demo
{
public class Program
{
public static void Main(string[] args)
{
int[,] arr1 = new int[10, 10];
int i, j;
Console.Write("Nhập ma trận 3x3: ");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
arr1[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
}
}
}
Cách tốt hơn - nhập cả dòng rồi parse:
// Nhập: "1 2 3"
string line = Console.ReadLine();
int[] row = line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray();
Hoặc dùng Scanner pattern:
static int ReadInt() => int.Parse(Console.ReadLine()); static int[] ReadInts() => Console.ReadLine().Split().Select(int.Parse).ToArray();
Lưu ý: Convert.ToInt16 trả short (16-bit). Thường dùng int.Parse hoặc int.TryParse an toàn hơn.