C語言中列印陣列的下三角矩陣和上三角矩陣的程式
程式描述
編寫一個程式來列印陣列的下三角矩陣和上三角矩陣。
三角矩陣
三角矩陣是指下三角矩陣或上三角矩陣。
下三角矩陣
如果方陣的主對角線以上的所有元素都為零,則稱為下三角矩陣。
上三角矩陣
如果方陣的主對角線以下的所有元素都為零,則稱為上三角矩陣。
形式為
$${\displaystyle L={\begin{bmatrix}\ell _{1,1}&&&&0\\ell _{2,1}&\ell _{2,2}&&&\\ell _{3,1}&\ell _{3,2}&\ddots &&\\vdots &\vdots &\ddots &\ddots &\\ell _{n,1}&\ell _{n,2}&\ldots &\ell _{n,n-1}&\ell _{n,n}\end{bmatrix}}}$$
的矩陣稱為**下三角矩陣或左三角矩陣**,類似地,形式為
$${\displaystyle U={\begin{bmatrix}u_{1,1}&u_{1,2}&u_{1,3}&\ldots &u_{1,n}\&u_{2,2}&u_{2,3}&\ldots &u_{2,n}\&&\ddots &\ddots &\vdots \&&&\ddots &u_{n-1,n}\0&&&&u_{n,n}\end{bmatrix}}}$$
的矩陣稱為上三角矩陣或右三角矩陣。下三角矩陣或左三角矩陣通常用變數L表示,上三角矩陣或右三角矩陣通常用變數U或R表示。
既是上三角矩陣又是下三角矩陣的矩陣是**對角矩陣**。與三角矩陣相似的矩陣稱為**可三角化矩陣**。
示例 - 上三角矩陣
$${\displaystyle {\begin{bmatrix}{1}&{4}&{1}\{0}&{6}&{4}\{0}&{0}&{1}\end{bmatrix}}}$$
示例 - 下三角矩陣
$${\displaystyle {\begin{bmatrix}{1}&{0}&{0}\{2}&{8}&{0}\{4}&{9}&{7}\end{bmatrix}}}$$
演算法
示例 - 不同維度的矩陣
對於下三角矩陣
找到行和列的索引位置。
如果列位置大於行位置,則將該位置設為0。
對於上三角矩陣
找到行和列的索引位置。
如果列位置小於行位置,則將該位置設為0。
示例
/* Program to find Lower and Upper Triangle Matrix */ #include<stdio.h> int main() { int rows, cols, r, c, matrix[10][10]; clrscr(); /*Clears the Screen*/ printf("Please enter the number of rows for the matrix: "); scanf("%d", &rows); printf("
"); printf("Please enter the number of columns for the matrix: "); scanf("%d", &cols); printf("
"); printf("Please enter the elements for the Matrix:
"); for(r = 0; r < rows; r++){ for(c = 0;c < cols;c++){ scanf("%d", &matrix[r][c]); } } printf("
The Lower Triangular Matrix is: "); for(r = 0; r < rows; r++){ printf("
"); for(c = 0; c < cols; c++){ if(r >= c){ printf("%d\t ", matrix[r][c]); } else{ printf("0"); printf("\t"); } } } printf("
The Upper Triangular Matrix is: "); for(r = 0; r < rows; r++){ printf("
"); for(c = 0; c < cols; c++){ if(r > c){ printf("0"); printf("\t"); } else{ printf("%d\t ", matrix[r][c]); } } } getch(); return 0; }