C 语言查找下三角矩阵程序

如何用 C 语言编写查找下三角矩阵的程序并附带示例?下三角矩阵是主对角线上方的元素为零的方阵。

C Program to find Lower Triangle Matrix 0

C 语言查找下三角矩阵示例程序

此程序允许用户输入矩阵的行数和列数。接下来,此 C 程序将使用 For 循环查找此矩阵的下三角。

#include<stdio.h>

int main()
{
int i, j, rows, columns, a[10][10];

printf("\n Please Enter Number of rows and columns : ");
scanf("%d %d", &i, &j);

printf("\n Please Enter the Matrix Elements \n");
for(rows = 0; rows < i; rows++)
{
for(columns = 0;columns < j;columns++)
{
scanf("%d", &a[rows][columns]);
}
}

for(rows = 0; rows < i; rows++)
{
printf("\n");
for(columns = 0; columns < j; columns++)
{
if(rows >= columns)
{
printf("%d ", a[rows][columns]);
}
else
{
printf("0 ");
}
}
}

return 0;
}

矩阵下三角输出。

 Please Enter Number of rows and columns  :  2 2

 Please Enter the Matrix Elements 
10 20
30 40

10 0  
30 40 

在此 C 语言查找下三角矩阵的程序中,我们声明了一个大小为 10 * 10 的二维数组。下面的 C 编程 语句要求用户输入矩阵大小(行数和列数)。例如 2 行,2 列 = a[2][2])。

printf("\n Please Enter Number of rows and columns  :  ");
scanf("%d %d", &i, &j);

接下来,我们使用 for 循环遍历 a[2][2] 矩阵中的每个单元格。`for` 循环中的条件 ((rows < i) 和 (columns < j)) 将确保编译器不会超出 矩阵 的限制。否则,矩阵将溢出。

for 循环中的 scanf 语句会将用户输入的值存储在每个单独的数组元素中,例如 a[0][0]、a[0][1] 等。

for(rows = 0; rows < i; rows++).
{
  for(columns = 0; columns < j; columns++)
   {
     scanf("%d", &a[rows][columns]);
   }
}

在下一行 程序 中,我们有另一个 for 循环来查找矩阵的下三角。

for(rows = 0; rows < i; rows++)
{
	printf("\n");
	for(columns = 0; columns < j; columns++)
    	{
    		if(rows >= columns)
    		{
    			printf("%d ", a[rows][columns]);
		}
		else
		{
			printf("0  ");
		}
 	}
}

用户为 C 语言查找下三角矩阵输入的 are: a[2][2] = {{10, 20}, { 30, 40}}

行第一次迭代: for(rows = 0; rows < 2; 0++)
条件 (0 < 2) 为真。

列第一次迭代: for(columns = 0; 0 < 2; 0++)
条件 (columns < 2) 为真。因此,它将开始执行循环内的语句。

if(rows >= columns) => if(0 >= 0) – 此条件为真。因此,它将打印 a[0][0] = 10

列第二次迭代: for(columns = 1; 1 < 2; 1++)
条件 (columns < 2) 为真。

if(rows >= columns)=> if(0 >= 1) – 此条件为假。因此,它将打印 0

列第三次迭代: for(columns = 2; 2 < 2; 2++)
条件 (columns < 2) 为假。因此,它将退出循环。

接下来,rows 的值将增加到 1。

行第二次迭代: for(rows = 1; rows < 2; 1++)
条件 (1 < 2) 为真。

列第一次迭代: for(columns = 0; 0 < 2; 0++)
条件 (columns < 2) 为真。因此,它将开始执行循环内的语句。

if(rows >= columns) => if(1 >= 0) – 此条件为假。因此,它将打印 a[1][0] = 30

列第二次迭代: for(columns = 1; 1 < 2; 1++)
条件 (columns < 2) 为真。

if(rows >= columns) => if(1 >= 1) – 条件为真。因此,它将打印 a[1][1] = 40

列第三次迭代: for(columns = 2; 2 < 2; 2++)
条件 (columns < 2) 为假。因此,它将退出循环。

接下来,rows 的值将增加到 1。增加后,第一个 for 循环内的条件 (rows < 2) 将失败。因此,它将退出循环。

让我用 3*3 矩阵尝试同样的操作。

C Program to find Lower Triangle Matrix 2

评论已关闭。