C语言程序,用于检查给定矩阵是否为稀疏矩阵


2022 年 2 月 3 日, Learn eTutorial
1870

为了更好地理解,我们始终建议您学习下面列出的C语言编程基础主题

什么是稀疏矩阵?

在此程序中,我们需要检查给定矩阵是否为稀疏矩阵。稀疏矩阵是指零元素多于非零元素的矩阵;它用于存储具有大量零元素的元素。稀疏矩阵的一个示例如下所示。

A=
5 0 0
0 4 0
3 0 0

在这里,矩阵a有 6 个零元素和三个非零元素,因此我们可以将矩阵a称为 稀疏矩阵

在此示例中,我们需要检查矩阵中有多少个零和非零元素。因此,我们接受一个矩阵,然后启动一个 for 循环 来检查矩阵的每个元素,然后我们使用一个计数器,并且每当我们遇到一个零元素时就增加该计数器。现在我们检查计数器是否大于“[m*n]/2”;如果正确,我们将其打印为稀疏矩阵。否则,我们打印不是稀疏矩阵。这是一个简单的矩阵c程序。

算法

步骤1:包含头文件以在C程序中使用内置函数。

步骤2:声明变量 i,j,m,n,counter,m1[10][10] 为整数。

步骤3:从用户读取矩阵的阶数到变量 m n 中。

步骤4:使用 for 循环 读取矩阵的系数到矩阵 m1[i[j] 中。

步骤5:检查 m1[i][j]=0,如果为真则将计数器加 1,并重复步骤4。

步骤6:检查 if counter>(m*n)/2,然后显示给定矩阵为稀疏矩阵。 否则 执行步骤7。

步骤7:否则显示给定矩阵不是稀疏矩阵。

步骤8:使用 printf 函数显示有 counter 个零。

C 语言源代码

                                          #include <stdio.h>

void main()
{
  static int m1[10][10];
  int i, j, m, n;
  int counter = 0;
  printf("Enter the order of the matix\n");
  scanf("%d %d", & m, & n);
  printf("Enter the coefficients of the matix\n");
  for (i = 0; i < m; ++i)
  {
    for (j = 0; j < n; ++j)
    {
      scanf("%d", & m1[i][j]);
      if (m1[i][j] == 0)
      {
        ++counter;
      }
    }
  }
  if (counter > ((m * n) / 2))
  {
    printf("The given matrix is a sparse matrix \n");
  } else
    printf("The given matrix is not a sparse matrix \n");
    printf("There are %d number of zeros", counter);
} /* EN dof main() */ /*end of main() */
                                      

输出

Enter the order of the matrix
2*2

Enter the coefficients of the matrix
1 2
3 4

The given matrix is not a sparse matrix
There are 0 number of zeros

Run 2

Enter the order of the matrix
3*3

Enter the co-efficiency of the matrix
1 0 0
0 0 1
0 1 0
The given matrix is a sparse matrix

There are 6 number of zeros