Verificando Matriz Esparsa

CBeginner
Pratique Agora

Introdução

Uma matriz esparsa (sparse matrix) é uma matriz na qual o número de zeros é maior que o número de elementos não nulos. Neste laboratório passo a passo, aprenderemos como verificar se um array bidimensional é uma matriz esparsa ou não, usando a linguagem de programação C.

Nota: Você precisa criar o arquivo ~/project/main.c por conta própria para praticar a codificação e aprender como compilar e executá-lo usando o gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Criando um Array Bidimensional

Nesta etapa, criaremos um array bidimensional para armazenar os elementos da nossa matriz. Receberemos a entrada do usuário para o número de linhas e colunas e, em seguida, pediremos ao usuário para inserir os elementos da matriz um por um, usando um loop for aninhado.

#include <stdio.h>

int main()
{
   int matrix[10][10], row, column, i, j;
   printf("Enter the number of rows and columns of the matrix:\n");
   scanf("%d%d", &row, &column);

   printf("Enter the elements of the matrix:\n");
   for (i = 0; i < row; i++)
   {
      for (j = 0; j < column; j++)
      {
         scanf("%d", &matrix[i][j]);
      }
   }

   // Checking if the matrix is sparse or not
    int counter = 0;
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < column; j++)
        {
            if (matrix[i][j] == 0)
                counter++;
        }
    }

    if(counter > (row * column) / 2)
        printf("The matrix is a sparse matrix\n");
    else
        printf("The matrix is not a sparse matrix\n");

   return 0;
}

Imprimir a Matriz

Aqui, imprimiremos a matriz usando o loop for aninhado no qual já recebemos a entrada do usuário.

#include <stdio.h>

int main()
{
   int matrix[10][10], row, column, i, j;
   printf("Enter the number of rows and columns of the matrix:\n");
   scanf("%d%d", &row, &column);

   printf("Enter the elements of the matrix:\n");
   for (i = 0; i < row; i++)
   {
      for (j = 0; j < column; j++)
      {
         scanf("%d", &matrix[i][j]);
      }
   }

   // Printing the matrix
   printf("The matrix:\n");
   for (i = 0; i < row; i++)
   {
      for (j = 0; j < column; j++)
      {
         printf("%d ", matrix[i][j]);
      }
      printf("\n");
   }

   // Checking if the matrix is sparse or not
    int counter = 0;
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < column; j++)
        {
            if (matrix[i][j] == 0)
                counter++;
        }
    }

    if(counter > (row * column) / 2)
        printf("The matrix is a sparse matrix\n");
    else
        printf("The matrix is not a sparse matrix\n");

   return 0;
}

Completar o Programa

Aqui, adicionaremos os toques finais ao nosso programa. Verificaremos se a matriz fornecida pelo usuário é uma matriz esparsa (sparse matrix) ou não. Em seguida, imprimiremos o resultado, indicando se é ou não uma matriz esparsa.

#include <stdio.h>

int main()
{
   int matrix[10][10], row, column, i, j;
   printf("Enter the number of rows and columns of the matrix:\n");
   scanf("%d%d", &row, &column);

   printf("Enter the elements of the matrix:\n");
   for (i = 0; i < row; i++)
   {
      for (j = 0; j < column; j++)
      {
         scanf("%d", &matrix[i][j]);
      }
   }

   // Printing the matrix
   printf("The matrix:\n");
   for (i = 0; i < row; i++)
   {
      for (j = 0; j < column; j++)
      {
         printf("%d ", matrix[i][j]);
      }
      printf("\n");
   }

   // Checking if the matrix is sparse or not
    int counter = 0;
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < column; j++)
        {
            if (matrix[i][j] == 0)
                counter++;
        }
    }

    if(counter > (row * column) / 2)
        printf("The matrix is a sparse matrix\n");
    else
        printf("The matrix is not a sparse matrix\n");

   return 0;
}

Resumo

Neste laboratório passo a passo, aprendemos como verificar se um array bidimensional é esparso (sparse) ou não. Aprendemos sobre o conceito de uma matriz esparsa e como codificar na linguagem de programação C para determinar se uma matriz é esparsa ou não. Criamos um array bidimensional, recebemos a entrada do usuário, imprimimos a matriz e, finalmente, escrevemos a lógica para verificar se a matriz fornecida é esparsa ou não.