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;
}输出

数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP