Suma y resta de matrices en C

CCBeginner
Practicar Ahora

💡 Este tutorial está traducido por IA desde la versión en inglés. Para ver la versión original, puedes hacer clic aquí

Introducción

En este laboratorio, aprenderás a realizar la suma y resta de matrices en el lenguaje de programación C. Este programa pedirá al usuario que ingrese dos matrices del mismo tamaño y luego realizará la operación de suma y resta, imprimiendo las matrices resultantes.

Nota: Debes crear el archivo ~/project/main.c por ti mismo para practicar la codificación y aprender cómo compilarlo y ejecutarlo utilizando gcc.

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

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/ControlFlowGroup(["Control Flow"]) c(("C")) -.-> c/CompoundTypesGroup(["Compound Types"]) c(("C")) -.-> c/FunctionsGroup(["Functions"]) c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c/BasicsGroup -.-> c/variables("Variables") c/BasicsGroup -.-> c/data_types("Data Types") c/BasicsGroup -.-> c/operators("Operators") c/ControlFlowGroup -.-> c/for_loop("For Loop") c/CompoundTypesGroup -.-> c/arrays("Arrays") c/FunctionsGroup -.-> c/function_declaration("Function Declaration") c/UserInteractionGroup -.-> c/user_input("User Input") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/variables -.-> lab-123195{{"Suma y resta de matrices en C"}} c/data_types -.-> lab-123195{{"Suma y resta de matrices en C"}} c/operators -.-> lab-123195{{"Suma y resta de matrices en C"}} c/for_loop -.-> lab-123195{{"Suma y resta de matrices en C"}} c/arrays -.-> lab-123195{{"Suma y resta de matrices en C"}} c/function_declaration -.-> lab-123195{{"Suma y resta de matrices en C"}} c/user_input -.-> lab-123195{{"Suma y resta de matrices en C"}} c/output -.-> lab-123195{{"Suma y resta de matrices en C"}} end

Configurar el programa

Primero, configura el programa incluyendo las bibliotecas necesarias y definiendo la función principal.

#include<stdio.h>

int main()
{
    // Add code here
}

Declarar variables

Declara las variables necesarias en la función principal. Necesitamos 2 matrices, una para cada entrada, y 2 matrices para almacenar el resultado de las operaciones de suma y resta.

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

n y m son el número de filas y columnas de las matrices.

first y second son las matrices de entrada.

sum y diff son las matrices que almacenarán el resultado de las operaciones de suma y resta, respectivamente.

Solicitar entrada del usuario

Utiliza la función scanf() para preguntar al usuario el número de filas y columnas de las matrices y luego pídeles que ingresen los elementos de las matrices.

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]);

Mostrar las matrices de entrada

Utiliza la función printf() para mostrar las matrices 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");
}

Suma de matrices

Suma los elementos correspondientes de las dos matrices y almacena el resultado en la matriz de suma.

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

Mostrar el resultado de la suma

Utiliza la función printf() para mostrar la matriz de suma.

// 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");
}

Resta de matrices

Resta los elementos correspondientes de las dos matrices y almacena el resultado en la matriz de diferencia.

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

Mostrar el resultado de la resta

Utiliza la función printf() para mostrar la matriz de diferencia.

// 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

Aquí está el código final del 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;
}

Resumen

En este laboratorio, has aprendido el proceso de suma y resta de matrices en el lenguaje de programación C. Has creado un programa que solicita al usuario que ingrese dos matrices del mismo tamaño y luego realiza operaciones de suma y resta, mostrando los resultados en la pantalla.