Đối với ma trận tam giác phía trên, hãy đặt tất cả các phần tử bên dưới đường chéo chính bằng 0.
Đặt điều kiện sau -
if (i <= j)
Console.Write(A[i, j] + "\t");
else
Console.Write("0\t"); Điều kiện trên sẽ đặt 0 cho các phần tử ma trận bên dưới đường chéo chính.
Ví dụ
Bạn có thể thử chạy mã sau để hiển thị ma trận tam giác trên.
using System;
using System.Linq;
class Demo {
static void Main() {
int m, n, i, j;
Console.Write("Enter number of rows and columns of the matrix ");
m = Convert.ToInt16(Console.ReadLine());
n = Convert.ToInt16(Console.ReadLine());
int[,] A = new int[10, 10];
Console.Write("\nEnter elements: ");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
A[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
Console.WriteLine("\nUpper Triangular Matrix ");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
Console.Write(A[i, j] + "\t");
}
Console.WriteLine();
}
for (i = 0; i < m; i++) {
Console.Write("\n");
for (j = 0; j < 3; j++) {
if (i >= j)
Console.Write(A[i, j] + "\t");
else
Console.Write("0\t");
}
}
Console.ReadLine();
}
} Đầu ra
Enter number of rows and columns of the matrix Enter elements: Upper Triangular Matrix