Adição e Subtração de Matrizes em C

CBeginner
Pratique Agora

Introdução

Neste laboratório, você aprenderá a realizar adição e subtração de matrizes na linguagem de programação C. Este programa solicitará ao usuário que insira duas matrizes do mesmo tamanho e, em seguida, executará a operação de adição e subtração, imprimindo as matrizes resultantes.

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

Configurar o programa

Primeiramente, configure o programa incluindo as bibliotecas necessárias e definindo a função principal (main function).

#include<stdio.h>

int main()
{
    // Add code here
}

Declarar variáveis

Declare as variáveis necessárias na função principal (main function). Precisamos de 2 matrizes, uma para cada entrada, e 2 matrizes para armazenar o resultado das operações de adição e subtração.

int n, m, c, d, first[10][10], second[10][10], sum[10][10], diff[10][10];

n e m são o número de linhas e colunas das matrizes.

first e second são as matrizes de entrada.

sum e diff são as matrizes que armazenarão o resultado das operações de adição e subtração, respectivamente.

Obter entrada do usuário

Use a função scanf() para solicitar ao usuário o número de linhas e colunas das matrizes e, em seguida, pedir que ele insira os elementos das matrizes.

printf("\nEnter the number of rows and columns of the first matrix \n\n");
scanf("%d%d", &m, &n);

printf("\nEnter the %d elements of the first matrix \n\n", m*n);
for(c = 0; c < m; c++)   // to iterate the rows
    for(d = 0; d < n; d++)   // to iterate the columns
        scanf("%d", &first[c][d]);

printf("\nEnter the %d elements of the second matrix \n\n", m*n);
for(c = 0; c < m; c++)   // to iterate the rows
    for(d = 0; d < n; d++)   // to iterate the columns
        scanf("%d", &second[c][d]);

Exibir as matrizes de entrada

Use a função printf() para exibir as matrizes de entrada.

/*
    printing the first matrix
*/
printf("\n\nThe first matrix is: \n\n");
for(c = 0; c < m; c++)   // to iterate the rows
{
    for(d = 0; d < n; d++)   // to iterate the columns
    {
        printf("%d\t", first[c][d]);
    }
printf("\n");
}

/*
    printing the second matrix
*/
printf("\n\nThe second matrix is: \n\n");
for(c = 0; c < m; c++)   // to iterate the rows
{
    for(d = 0; d < n; d++)   // to iterate the columns
    {
        printf("%d\t", second[c][d]);
    }
printf("\n");
}

Adição de matrizes

Some os elementos correspondentes das duas matrizes e armazene o resultado na matriz soma.

for(c = 0; c < m; c++)
    for(d = 0; d < n; d++)
        sum[c][d] = first[c][d] + second[c][d];

Exibir o resultado da adição

Use a função printf() para exibir a matriz soma.

// printing the elements of the sum matrix
printf("\n\nThe sum of the two entered matrices is: \n\n");
for(c = 0; c < m; c++)
{
    for(d = 0; d < n; d++)
    {
        printf("%d\t", sum[c][d]);
    }
    printf("\n");
}

Subtração de Matrizes

Subtraia os elementos correspondentes das duas matrizes e armazene o resultado na matriz diff.

for(c = 0; c < m; c++)
    for(d = 0; d < n; d++)
        diff[c][d] = first[c][d] - second[c][d];

Exibir o resultado da subtração

Use a função printf() para exibir a matriz diff.

// printing the elements of the diff matrix
printf("\n\nThe difference(subtraction) of the two entered matrices is: \n\n");
for(c = 0; c < m; c++)
{
    for(d = 0; d < n; d++)
    {
        printf("%d\t", diff[c][d]);
    }
    printf("\n");
}

Código final

Aqui está o código final para o programa:

#include<stdio.h>

int main()
{
    int n, m, c, d, first[10][10], second[10][10], sum[10][10], diff[10][10];
    printf("\nEnter the number of rows and columns of the first matrix \n\n");
    scanf("%d%d", &m, &n);

    printf("\nEnter the %d elements of the first matrix \n\n", m*n);
    for(c = 0; c < m; c++)   // to iterate the rows
        for(d = 0; d < n; d++)   // to iterate the columns
            scanf("%d", &first[c][d]);

    printf("\nEnter the %d elements of the second matrix \n\n", m*n);
    for(c = 0; c < m; c++)   // to iterate the rows
        for(d = 0; d < n; d++)   // to iterate the columns
            scanf("%d", &second[c][d]);

    /*
        printing the first matrix
    */
    printf("\n\nThe first matrix is: \n\n");
    for(c = 0; c < m; c++)   // to iterate the rows
    {
        for(d = 0; d < n; d++)   // to iterate the columns
        {
            printf("%d\t", first[c][d]);
        }
    printf("\n");
    }

    /*
        printing the second matrix
    */
    printf("\n\nThe second matrix is: \n\n");
    for(c = 0; c < m; c++)   // to iterate the rows
    {
        for(d = 0; d < n; d++)   // to iterate the columns
        {
            printf("%d\t", second[c][d]);
        }
    printf("\n");
    }

    /*
        finding the SUM of the two matrices
        and storing in another matrix sum of the same size
    */
    for(c = 0; c < m; c++)
        for(d = 0; d < n; d++)
            sum[c][d] = first[c][d] + second[c][d];

    // printing the elements of the sum matrix
    printf("\n\nThe sum of the two entered matrices is: \n\n");
    for(c = 0; c < m; c++)
    {
        for(d = 0; d < n; d++)
        {
            printf("%d\t", sum[c][d]);
        }
        printf("\n");
    }

    /*
        finding the DIFFERENCE of the two matrices
        and storing in another matrix difference of the same size
    */
    for(c = 0; c < m; c++)
        for(d = 0; d < n; d++)
            diff[c][d] = first[c][d] - second[c][d];

    // printing the elements of the diff matrix
    printf("\n\nThe difference(subtraction) of the two entered matrices is: \n\n");
    for(c = 0; c < m; c++)
    {
        for(d = 0; d < n; d++)
        {
            printf("%d\t", diff[c][d]);
        }
        printf("\n");
    }

    return 0;
}

Resumo

Neste laboratório, você aprendeu o processo de adição e subtração de matrizes na linguagem de programação C. Você criou um programa que solicita ao usuário que insira duas matrizes do mesmo tamanho e, em seguida, realiza operações de adição e subtração, exibindo os resultados na tela.