C 程序检查矩阵是否为稀疏矩阵

如何编写 C 程序来检查矩阵是否是稀疏矩阵,并附带示例。任何矩阵,如果包含大量的零,都被称为稀疏矩阵。稀疏矩阵背后的数学公式是 T >= (m * n )/2,其中 T 是零的总数。

C 程序检查矩阵是否为稀疏矩阵示例

此稀疏矩阵程序允许用户输入矩阵的行数和列数。接下来,我们将使用 For 循环检查给定的矩阵是否为稀疏矩阵。

 #include<stdio.h>
 
int main()
{
 	int i, j, rows, columns, a[10][10], Total = 0;
  
 	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++)
  	{
   		for(columns = 0; columns < j; columns++)
    	{
    		if(a[rows][columns] == 0)
    		{
    			Total++;    		
			}
   	 	}
  	}
  	if(Total > (rows * columns)/2)
  	{
  		printf("\n The Matrix that you entered is a Sparse Matrix ");
	}
	else
	{
		printf("\n The Matrix that you entered is Not a Sparse Matrix ");
	}
  	
 	return 0;
}
C Program to check Matrix is a Sparse Matrix or Not 1

在此程序稀疏矩阵中,我们声明了大小为 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) and (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(rows = 0; rows < i; rows++)
{
	for(columns = 0; columns < j; columns++)
    	{
    		if(a[rows][columns] == 0)
    		{
    			Total++;    		
		}
 	}
}

用户在此 C 程序中插入的值(用于检查矩阵是否为稀疏矩阵)为:a[3][3] = {{10, 20, 0}, { 0, 0, 0},{0, 0, 70}}

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

列第一次迭代: for(columns = 0; 0 < 3; 0++)
条件 (columns < 3) 为真。

if(a[rows][columns] == 0) => if(a[0][0] == 0) – 此条件为 False。因此,它将退出 If 语句。

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

if(a[0][1] == 0) – 此条件为 False。

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

if(a[0][2] == 0) – 此条件为 True。因此,Total 将增至 1。

对这个稀疏矩阵 程序 的其余迭代执行相同的操作。

接下来,我们使用 If 语句 来检查零的总数是否大于或等于 (rows * columns) /2。

让我尝试使用其他值来运行稀疏矩阵程序。

Please Enter Number of rows and columns  :  3 3

 Please Enter the Matrix Elements 
10 20 30
0 0 0
25 59 0

 The Matrix that you entered is Not a Sparse Matrix

评论已关闭。