C++ 中检查矩阵是否为上三角形的程序
给定一个方阵 M[r][c],其中“r”是行数,“c”是列数,且 r = c,我们要检查“M”是否是上三角形矩阵。
上三角形矩阵
上三角形矩阵是指主对角线(包括主对角线)以上元素不为零,以下元素都为零的矩阵。
例如以下示例 −

在上图中,以红色高亮的元素是主对角线以下的元素,都为零,而其余元素都非零。
示例
Input: m[3][3] = { {1, 2, 3},
{0, 5, 6},
{0, 0, 9}}
Output: yes
Input: m[3][3] == { {3, 0, 1},
{6, 2, 0},
{7, 5, 3} }
Output: no算法
Start
Step 1 -> define macro as #define size 4
Step 2 -> Declare function to check matrix is lower triangular matrix
bool check(int arr[size][size])
Loop For int i = 1 and i < size and i++
Loop For int j = 0 and j < i and j++
IF (arr[i][j] != 0)
return false
End
End
End
Return true
Step 3 -> In main()
Declare int arr[size][size] = { { 1, 1, 3, 2 },
{ 0, 3, 3, 2 },
{ 0, 0, 2, 1 },
{ 0, 0, 0, 1 } }
IF (check(arr))
Print its a lower triangular matrix
End
Else
Print its not a lower triangular matrix
End
Stop示例
#include <bits/stdc++.h>
#define size 4
using namespace std;
// check matrix is lower triangular matrix
bool check(int arr[size][size]){
for (int i = 1; i < size; i++)
for (int j = 0; j < i; j++)
if (arr[i][j] != 0)
return false;
return true;
}
int main(){
int arr[size][size] = { { 1, 1, 3, 2 },
{ 0, 3, 3, 2 },
{ 0, 0, 2, 1 },
{ 0, 0, 0, 1 } };
if (check(arr))
cout << "its a lower triangular matrix";
else
cout << "its not a lower triangular matrix";
return 0;
}输出
its a lower triangular matrix
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP