C 语言查找矩阵的迹

编写一个 C 程序,使用 for 循环查找矩阵的迹。矩阵的迹是其对角线元素之和。在此 C 示例中,if(i == j) 用于查找矩阵对角线元素并将其加到迹中。

#include <stdio.h>

int main()
{
	int i, j, rows, columns, trace = 0;

	printf("Enter Matrix Rows and Columns =  ");
	scanf("%d %d", &rows, &columns);

	int Tra_arr[rows][columns];

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

	for (i = 0; i < rows; i++)
	{
		for (j = 0; j < columns; j++)
		{
			if (i == j)
			{
				trace = trace + Tra_arr[i][j];
			}
		}
	}

	printf("The Trace Of the Matrix = %d\n", trace);
}
C Program to Find the Trace of a Matrix

使用 while 循环查找矩阵迹的 C 程序。

#include <stdio.h>

int main()
{
		
		int i, j, rows, columns, trace = 0;	
		
		printf("Enter Matrix Rows and Columns =  ");
		scanf("%d %d", &rows, &columns);
		
		int Tra_arr[rows][columns];
		
		printf("Please Enter the Matrix Items =  \n");
		i = 0; 
		while(i < rows) 
		{
			j = 0; 
			while(j < columns) 
			{
				scanf("%d", &Tra_arr[i][j]);
				j++;
			}	
			i++;
		}
		
		i = 0; 
		while(i < rows) 
		{
			j = 0; 
			while(j < columns) 
			{
				if(i == j)
				{
					trace = trace + Tra_arr[i][j];
				}
				j++;
			}	
			i++;
		}
		
		printf("The Trace Of the Matrix = %d\n", trace);

}
Enter Matrix Rows and Columns =  3 3
Please Enter the Matrix Items =  
10 30 50
70 90 120
150 170 290
The Trace Of the Matrix = 390

C 示例使用 do while 循环计算并打印给定矩阵的迹。

#include <stdio.h>

int main()
{

	int i, j, rows, columns, trace = 0;

	printf("Enter Matrix Rows and Columns =  ");
	scanf("%d %d", &rows, &columns);

	int Tra_arr[rows][columns];

	printf("Please Enter the Matrix Items =  \n");
	i = 0;
	do
	{
		j = 0;
		do
		{
			scanf("%d", &Tra_arr[i][j]);
			if (i == j)
			{
				trace = trace + Tra_arr[i][j];
			}
		} while (++j < columns);
	} while (++i < rows);

	printf("The Trace Of the Matrix = %d\n", trace);
}
Enter Matrix Rows and Columns =  3 3
Please Enter the Matrix Items =  
10 20 30
40 50 60
70 80 90
The Trace Of the Matrix = 150