Addition et soustraction de matrices en C

CCBeginner
Pratiquer maintenant

💡 Ce tutoriel est traduit par l'IA à partir de la version anglaise. Pour voir la version originale, vous pouvez cliquer ici

Introduction

Dans ce laboratoire, vous apprendrez à effectuer l'addition et la soustraction de matrices en langage de programmation C. Ce programme demandera à l'utilisateur d'entrer deux matrices de même taille, puis effectuera les opérations d'addition et de soustraction, et affichera les matrices résultantes.

Note : Vous devez créer le fichier ~/project/main.c vous-même pour pratiquer la programmation et apprendre à le compiler et à l'exécuter à l'aide de 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{{"Addition et soustraction de matrices en C"}} c/data_types -.-> lab-123195{{"Addition et soustraction de matrices en C"}} c/operators -.-> lab-123195{{"Addition et soustraction de matrices en C"}} c/for_loop -.-> lab-123195{{"Addition et soustraction de matrices en C"}} c/arrays -.-> lab-123195{{"Addition et soustraction de matrices en C"}} c/function_declaration -.-> lab-123195{{"Addition et soustraction de matrices en C"}} c/user_input -.-> lab-123195{{"Addition et soustraction de matrices en C"}} c/output -.-> lab-123195{{"Addition et soustraction de matrices en C"}} end

Configurer le programme

Tout d'abord, configurez le programme en incluant les bibliothèques nécessaires et en définissant la fonction principale.

#include<stdio.h>

int main()
{
    // Add code here
}

Déclarer les variables

Déclarez les variables nécessaires dans la fonction principale. Nous avons besoin de 2 matrices, une pour chaque entrée, et de 2 matrices pour stocker le résultat des opérations d'addition et de soustraction.

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

n et m sont le nombre de lignes et de colonnes des matrices.

first et second sont les matrices d'entrée.

sum et diff sont les matrices qui stockeront respectivement le résultat des opérations d'addition et de soustraction.

Demander les entrées de l'utilisateur

Utilisez la fonction scanf() pour demander à l'utilisateur le nombre de lignes et de colonnes des matrices, puis demandez-lui d'entrer les éléments des 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]);

Afficher les matrices d'entrée

Utilisez la fonction printf() pour afficher les matrices d'entrée.

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

Addition de matrices

Ajoutez les éléments correspondants des deux matrices et stockez le résultat dans la matrice de somme.

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

Afficher le résultat de l'addition

Utilisez la fonction printf() pour afficher la matrice de somme.

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

Soustraction de matrices

Soustrayez les éléments correspondants des deux matrices et stockez le résultat dans la matrice de différence.

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

Afficher le résultat de la soustraction

Utilisez la fonction printf() pour afficher la matrice de différence.

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

Code final

Voici le code final du programme :

#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;
}

Résumé

Dans ce laboratoire, vous avez appris le processus d'addition et de soustraction de matrices en langage de programmation C. Vous avez créé un programme qui demande à l'utilisateur d'entrer deux matrices de même taille, puis effectue des opérations d'addition et de soustraction, affichant les résultats à l'écran.