คำอธิบายโปรแกรม
เขียนโปรแกรมพิมพ์เมทริกซ์สามเหลี่ยมล่าง (Lower Triangular) และเมทริกซ์สามเหลี่ยมบน (Upper Triangular) ของอาร์เรย์
เมทริกซ์สามเหลี่ยม (Triangular Matrix)
เมทริกซ์สามเหลี่ยม คือเมทริกซ์ที่เป็นสามเหลี่ยมล่าง หรือสามเหลี่ยมบน
เมทริกซ์สามเหลี่ยมล่าง (Lower Triangular Matrix)
เมทริกซ์สี่เหลี่ยมจัตุรัส เรียกว่า three-cornered ล่าง หากรายการทั้งหมดเหนือเส้นทแยงมุมหลักเป็นศูนย์
เมทริกซ์สามเหลี่ยมบน (Upper Triangular Matrix)
เมทริกซ์สี่เหลี่ยมจัตุรัส เรียกว่า three-cornered บน หากรายการทั้งหมดใต้เส้นทแยงมุมหลักเป็นศูนย์
เมทริกซ์รูปแบบ:
Lower: L = [[ℓ₁₁, 0, 0], [ℓ₂₁, ℓ₂₂, 0], [ℓ₃₁, ℓ₃₂, ℓ₃₃]]
Upper: U = [[u₁₁, u₁₂, u₁₃], [0, u₂₂, u₂₃], [0, 0, u₃₃]]
เมทริกซ์ที่เป็นทั้งบนและล่าง คือเมทริกซ์ทแยงมุม (Diagonal)
อัลกอริทึม
สำหรับเมทริกซ์สามเหลี่ยมล่าง: หาตำแหน่งแถวและคอลัมน์ หากตำแหน่งคอลัมน์ > แถว ให้กำหนดเป็น 0
สำหรับเมทริกซ์สามเหลี่ยมบน: หาตำแหน่งแถวและคอลัมน์ หากตำแหน่งคอลัมน์ < แถว ให้กำหนดเป็น 0
ตัวอย่างโค้ด
/* Program to find Lower and Upper Triangle Matrix */
#include <stdio.h>
int main() {
int rows, cols, r, c, matrix[10][10];
// clrscr();
printf("Please enter the number of rows for the matrix: ");
scanf("%d", &rows);
printf("\n");
printf("Please enter the number of columns for the matrix: ");
scanf("%d", &cols);
printf("\n");
printf("Please enter the elements for the Matrix: \n");
for (r = 0; r < rows; r++) {
for (c = 0; c < cols; c++) {
scanf("%d", &matrix[r][c]);
}
}
printf("\n The Lower Triangular Matrix is: ");
for (r = 0; r < rows; r++) {
printf("\n");
for (c = 0; c < cols; c++) {
if (r >= c) {
printf("%d\t ", matrix[r][c]);
} else {
printf("0\t");
}
}
}
printf("\n\n The Upper Triangular Matrix is: ");
for (r = 0; r < rows; r++) {
printf("\n");
for (c = 0; c < cols; c++) {
if (r > c) {
printf("0\t");
} else {
printf("%d\t ", matrix[r][c]);
}
}
}
// getch();
return 0;
}
เอาต์พุต
แสดงเมทริกซ์สามเหลี่ยมล่างและสามเหลี่ยมบน จากเมทริกซ์ที่ป้อนเข้าไป