Сложение и вычитание матриц на языке C

CCBeginner
Практиковаться сейчас

💡 Этот учебник переведен с английского с помощью ИИ. Чтобы просмотреть оригинал, вы можете перейти на английский оригинал

Введение

В этом практическом занятии (лабораторной работе) вы научитесь выполнять сложение и вычитание матриц на языке программирования C. Эта программа попросит пользователя ввести две матрицы одинакового размера, а затем выполнит операции сложения и вычитания, выведя результирующие матрицы.

Примечание: Вы должны создать файл ~/project/main.c самостоятельно, чтобы потренироваться в написании кода и узнать, как компилировать и запускать его с помощью 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/FunctionsGroup(["Functions"]) c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/ControlFlowGroup(["Control Flow"]) c(("C")) -.-> c/CompoundTypesGroup(["Compound Types"]) 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{{"Сложение и вычитание матриц на языке C"}} c/data_types -.-> lab-123195{{"Сложение и вычитание матриц на языке C"}} c/operators -.-> lab-123195{{"Сложение и вычитание матриц на языке C"}} c/for_loop -.-> lab-123195{{"Сложение и вычитание матриц на языке C"}} c/arrays -.-> lab-123195{{"Сложение и вычитание матриц на языке C"}} c/function_declaration -.-> lab-123195{{"Сложение и вычитание матриц на языке C"}} c/user_input -.-> lab-123195{{"Сложение и вычитание матриц на языке C"}} c/output -.-> lab-123195{{"Сложение и вычитание матриц на языке C"}} end

Настройка программы

Сначала настройте программу, подключив необходимые библиотеки и определив главную функцию.

#include<stdio.h>

int main()
{
    // Add code here
}

Объявление переменных

Объявите необходимые переменные в главной функции. Нам нужны 2 матрицы для каждого входного значения и 2 матрицы для хранения результатов операций сложения и вычитания.

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

n и m - это количество строк и столбцов матриц.

first и second - это входные матрицы.

sum и diff - это матрицы, которые будут хранить результаты операций сложения и вычитания соответственно.

Получение ввода от пользователя

Используйте функцию scanf(), чтобы запросить у пользователя количество строк и столбцов матриц, а затем попросить их ввести элементы матриц.

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

Вывод входных матриц

Используйте функцию printf(), чтобы вывести на экран входные матрицы.

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

Сложение матриц

Сложите соответствующие элементы двух матриц и сохраните результат в матрице суммы.

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

Вывод результата сложения

Используйте функцию printf(), чтобы вывести на экран матрицу суммы.

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

Вычитание матриц

Вычтите соответствующие элементы двух матриц и сохраните результат в матрице разности.

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

Вывод результата вычитания

Используйте функцию printf(), чтобы вывести на экран матрицу разности.

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

Финальный код

Вот окончательный код программы:

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

Резюме

В этом практическом занятии вы узнали процесс сложения и вычитания матриц на языке программирования C. Вы создали программу, которая запрашивает у пользователя ввод двух матриц одинакового размера, а затем выполняет операции сложения и вычитания, выводя результаты на экран.