Subtract Two Matrices in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to subtract two matrices in a C program. The lab covers the following steps:

First, you will learn how to read the dimensions and elements of two matrices from user input. You will create a C program that prompts the user to enter the number of rows and columns, and then the elements of the two matrices.

Next, you will implement the matrix subtraction operation, where you will subtract the corresponding elements of the two matrices and store the result in a new matrix. Finally, you will learn how to print the resulting matrix.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/UserInteractionGroup -.-> c/user_input("`User Input`") subgraph Lab Skills c/output -.-> lab-435200{{"`Subtract Two Matrices in C`"}} c/operators -.-> lab-435200{{"`Subtract Two Matrices in C`"}} c/for_loop -.-> lab-435200{{"`Subtract Two Matrices in C`"}} c/arrays -.-> lab-435200{{"`Subtract Two Matrices in C`"}} c/user_input -.-> lab-435200{{"`Subtract Two Matrices in C`"}} end

Read Dimensions and Elements

In this step, you will learn how to read matrix dimensions and elements from user input in a C program for matrix subtraction. We'll create a program that allows users to input the size and values of two matrices.

First, let's create a new C file for our matrix subtraction program:

cd ~/project
nano matrix_subtraction.c

Now, add the following code to the file:

#include <stdio.h>

#define MAX_SIZE 100

int main() {
    int rows, cols;
    int matrix1[MAX_SIZE][MAX_SIZE];
    int matrix2[MAX_SIZE][MAX_SIZE];

    // Read matrix dimensions
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    printf("Enter the number of columns: ");
    scanf("%d", &cols);

    // Input elements for the first matrix
    printf("Enter elements of the first matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix1[i][j]);
        }
    }

    // Input elements for the second matrix
    printf("Enter elements of the second matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix2[i][j]);
        }
    }

    return 0;
}

Example output:

Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the first matrix:
Enter element [0][0]: 5
Enter element [0][1]: 6
Enter element [1][0]: 7
Enter element [1][1]: 8
Enter elements of the second matrix:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [1][0]: 3
Enter element [1][1]: 4

Let's compile and run the program:

gcc matrix_subtraction.c -o matrix_subtraction
./matrix_subtraction

Code Explanation:

  • We define a maximum matrix size of 100x100 using MAX_SIZE
  • rows and cols store the dimensions of the matrices
  • Two 2D arrays matrix1 and matrix2 are created to store matrix elements
  • scanf() is used to read matrix dimensions and elements from user input
  • Nested loops are used to input elements for both matrices

Subtract Corresponding Elements

In this step, you will learn how to subtract corresponding elements of two matrices and store the result in a new matrix. We'll extend the previous program to perform matrix subtraction.

Open the existing file and modify the code:

cd ~/project
nano matrix_subtraction.c

Update the code with matrix subtraction logic:

#include <stdio.h>

#define MAX_SIZE 100

int main() {
    int rows, cols;
    int matrix1[MAX_SIZE][MAX_SIZE];
    int matrix2[MAX_SIZE][MAX_SIZE];
    int result[MAX_SIZE][MAX_SIZE];

    // Read matrix dimensions
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    printf("Enter the number of columns: ");
    scanf("%d", &cols);

    // Input elements for the first matrix
    printf("Enter elements of the first matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix1[i][j]);
        }
    }

    // Input elements for the second matrix
    printf("Enter elements of the second matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix2[i][j]);
        }
    }

    // Subtract corresponding elements
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result[i][j] = matrix1[i][j] - matrix2[i][j];
        }
    }

    return 0;
}

Example output:

Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the first matrix:
Enter element [0][0]: 5
Enter element [0][1]: 6
Enter element [1][0]: 7
Enter element [1][1]: 8
Enter elements of the second matrix:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [1][0]: 3
Enter element [1][1]: 4

Code Explanation:

  • A new 2D array result is created to store the subtraction results
  • Nested loops iterate through each matrix element
  • result[i][j] is calculated by subtracting corresponding elements from matrix1 and matrix2
  • The subtraction follows element-wise matrix subtraction rules

Let's compile the program:

gcc matrix_subtraction.c -o matrix_subtraction

Print the Resulting Matrix

In this step, you will learn how to print the resulting matrix after subtraction. We'll modify the previous program to display the subtraction results.

Open the existing file and update the code:

cd ~/project
nano matrix_subtraction.c

Update the code with matrix printing logic:

#include <stdio.h>

#define MAX_SIZE 100

int main() {
    int rows, cols;
    int matrix1[MAX_SIZE][MAX_SIZE];
    int matrix2[MAX_SIZE][MAX_SIZE];
    int result[MAX_SIZE][MAX_SIZE];

    // Read matrix dimensions
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    printf("Enter the number of columns: ");
    scanf("%d", &cols);

    // Input elements for the first matrix
    printf("Enter elements of the first matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix1[i][j]);
        }
    }

    // Input elements for the second matrix
    printf("Enter elements of the second matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix2[i][j]);
        }
    }

    // Subtract corresponding elements
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result[i][j] = matrix1[i][j] - matrix2[i][j];
        }
    }

    // Print the resulting matrix
    printf("\nResulting Matrix after Subtraction:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Compile and run the program:

gcc matrix_subtraction.c -o matrix_subtraction
./matrix_subtraction

Example output:

Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the first matrix:
Enter element [0][0]: 5
Enter element [0][1]: 6
Enter element [1][0]: 7
Enter element [1][1]: 8
Enter elements of the second matrix:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [1][0]: 3
Enter element [1][1]: 4

Resulting Matrix after Subtraction:
4 4
4 4

Code Explanation:

  • A new nested loop is added to print the result matrix
  • printf("%d ", result[i][j]) prints each element
  • An additional printf("\n") creates a new line after each row
  • The output shows the matrix with subtracted values

Summary

In this lab, you learned how to read matrix dimensions and elements from user input in a C program for matrix subtraction. The program allows users to input the size and values of two matrices, which are then stored in two 2D arrays. This step lays the foundation for the subsequent step of subtracting the corresponding elements of the two matrices and printing the resulting matrix.

The program prompts the user to enter the number of rows and columns, and then guides them through inputting the elements of the first and second matrices. This ensures that the program can properly handle matrices of different sizes and store the input data for further processing.

Other C Tutorials you may like