Add two matrices using the C programming language

Add two matrices using the C programming language
Posted on 30-08-2023

Add two matrices using the C programming language

Code:

#include <stdio.h>

int main() {
int rows, cols;

printf("Enter the number of rows: ");
scanf("%d", &rows);

printf("Enter the number of columns: ");
scanf("%d", &cols);

int matrix1[rows][cols], matrix2[rows][cols], result[rows][cols];

// Input 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++) {
scanf("%d", &matrix1[i][j]);
}
}

// Input 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++) {
scanf("%d", &matrix2[i][j]);
}
}

// Adding matrices
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Displaying the result matrix
printf("Resultant matrix after addition:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", result[i][j]);
}
printf("\n");
}

return 0;
}

 

Copy and paste this code into a C compiler, and it will prompt you to enter the number of rows and columns for the matrices, as well as the elements of the matrices. It will then calculate the sum of the two matrices and display the result.

Explanation:

#include <stdio.h>

This line includes the standard input-output library, which provides functions like printf and scanf for input and output operations.

int main() {

This is the starting point of the program. The main function is where the execution begins.

int rows, cols;

Declares two integer variables rows and cols to store the number of rows and columns for the matrices.

printf("Enter the number of rows: ");
scanf("%d", &rows);

Prints a message to the console asking the user to enter the number of rows and then reads the input from the user into the rows variable using scanf.

printf("Enter the number of columns: ");
scanf("%d", &cols);

Similar to the previous block, this prints a message for the user to enter the number of columns and reads the input into the cols variable.

int matrix1[rows][cols], matrix2[rows][cols], result[rows][cols];

Declares three 2D arrays: matrix1, matrix2, and result, each with dimensions based on the user-input rows and cols.

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

Displays a message prompting the user to enter the elements of the first matrix. Then, it uses nested loops to iterate through the rows and columns of matrix1, and scanf reads the input values and stores them in the appropriate positions of the array.

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

Similar to the previous block, this section prompts the user to enter the elements of the second matrix and reads the input into the matrix2 array.

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

This loop iterates through each element of the matrices matrix1 and matrix2, and for each element, it calculates the sum of the corresponding elements from both matrices and stores the result in the result matrix.

printf("Resultant matrix after addition:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", result[i][j]);
}
printf("\n");
}

This loop is responsible for printing the resulting matrix. It iterates through the result matrix and prints each element followed by a tab (\t). After each row is printed, a newline (\n) character is added to move to the next row.

return 0;
}

This statement indicates that the program has successfully executed and is now returning the value 0 to the operating system, which typically indicates a successful execution.

 

Algorithm:

  1. Include Header File:

    • Include the standard input-output header file <stdio.h>.

  2. Main Function:

    • Declare the main function to begin the program execution.

  3. Declare Variables:

    • Declare integer variables rows and cols to store the number of rows and columns.

    • Declare three 2D arrays matrix1, matrix2, and result to store the input matrices and the result of addition.

  4. Input Number of Rows and Columns:

    • Display a prompt asking the user to enter the number of rows.

    • Read the user input into the variable rows.

    • Display a prompt asking the user to enter the number of columns.

    • Read the user input into the variable cols.

  5. Input Elements of the First Matrix:

    • Display a message prompting the user to enter the elements of the first matrix.

    • Use nested loops to iterate through each element of matrix1:

      • For each row and column, read an integer from the user and store it in the corresponding position of matrix1.

  6. Input Elements of the Second Matrix:

    • Display a message prompting the user to enter the elements of the second matrix.

    • Use nested loops to iterate through each element of matrix2:

      • For each row and column, read an integer from the user and store it in the corresponding position of matrix2.

  7. Matrix Addition:

    • Use nested loops to iterate through each element of both matrix1 and matrix2:

      • Add the corresponding elements from both matrices and store the result in the corresponding position of the result matrix.

  8. Display Resultant Matrix:

    • Display a message indicating that the resultant matrix after addition will be displayed.

    • Use nested loops to iterate through each element of the result matrix:

      • Print each element followed by a tab character (\t).

      • After each row, print a newline character (\n) to move to the next line.

  9. Return Success:

    • Return 0 to the operating system to indicate successful execution.
  10. End of Program:

    • End the main function.

This algorithm outlines the step-by-step process that the program follows to take input matrices, add them element-wise, and then display the resulting matrix.

 

Time Complexity:

The time complexity of the above C program for adding two matrices is primarily determined by the nested loops used to iterate through the matrices and perform addition. Let's analyze the time complexity step by step:

  1. Input:

    • The input step involves reading the number of rows and columns, which takes constant time, O(1).

  2. Input Elements of Matrices:

    • There are two nested loops used to input elements for both matrix1 and matrix2. Each loop iterates rows times, and within each loop, another loop iterates cols times to input the elements. Therefore, the complexity for each matrix input step is O(rows * cols).

  3. Matrix Addition:

    • Another set of nested loops is used to iterate through the matrices and perform the addition. Again, each loop iterates rows times, and within each loop, another loop iterates cols times. The addition operation within each iteration takes constant time. Therefore, the complexity for the matrix addition step is O(rows * cols).

  4. Display Resultant Matrix:

    • Similar to the input steps, there are two nested loops used to display the elements of the resultant matrix. Each loop iterates rows times, and within each loop, another loop iterates cols times to print the elements. Therefore, the complexity for displaying the resultant matrix is O(rows * cols).

Considering all the steps together, the dominant factor in the time complexity is the nested loops used for inputting, adding, and displaying the matrices. Therefore, the overall time complexity of the program is:

O(rows * cols)

Where rows and cols are the number of rows and columns, respectively, entered by the user. The time complexity increases linearly with the size of the matrices.

 

Space Complexity:

The space complexity of the given C program for adding two matrices is determined by the memory used to store the matrices themselves, as well as any other variables used in the program. Let's analyze the space complexity step by step:

  1. Variables:

    • rows and cols: These variables store the number of rows and columns and each take constant space, O(1).

    • matrix1, matrix2, and result: These 2D arrays hold the input matrices and the resultant matrix. The space required for each of these matrices is O(rows * cols), as they each have 'rows' rows and 'cols' columns.

  2. Loop Variables:

    • The loop variables (i and j) used in the loops take constant space, O(1).

  3. Constants:

    • The constants used in the program (like the format strings in printf and scanf) take constant space, O(1).

Considering all these factors, the overall space complexity of the program is:

O(rows * cols)

Where rows and cols are the number of rows and columns entered by the user. The space complexity is dominated by the memory used to store the matrices, and it increases linearly with the size of the matrices.

Thank You