Saturday, 8 August 2026

Multiply Two Matrices

 Matrix multiplication is a fundamental operation widely used in computer science, mathematics, and real-world applications like graphics rendering, machine learning, and scientific simulations. 

Below, you’ll learn how to write a C program for multiplication of two matrices, exploring multiple methods to handle different scenarios effectively. 

Learning how to implement a C program to multiply two matrices is crucial for solving problems involving large datasets, transformations, and optimizations.

Coders' comments

Two matrices meet, their product shines, Master the logic, and your future aligns.

Option 1: C Program to Multiply Two Matrices Using Nested Loop

#include <stdio.h>

// Define matrix size (3x3)
#define SIZE 3   

int main() {

    // Input matrices
    int a[SIZE][SIZE], b[SIZE][SIZE];
    
    // Result matrix initialized with 0
    int result[SIZE][SIZE] = {0};
    
    // Loop variables
    int i, j, k;                          

    // Take input for first matrix
    printf("Enter elements of first matrix:\n");
    
    // Loop through rows
    for (i = 0; i < SIZE; i++) {
        
        // Loop through columns
        for (j = 0; j < SIZE; j++) {
            
            // Store element
            scanf("%d", &a[i][j]);            
        }
    }

    // Take input for second matrix
    printf("Enter elements of second matrix:\n");
    for (i = 0; i < SIZE; i++) {
        for (j = 0; j < SIZE; j++) {
            scanf("%d", &b[i][j]);
        }
    }

    // Perform matrix multiplication
    // Iterate rows of first matrix
    for (i = 0; i < SIZE; i++) {
        
        // Iterate columns of second matrix
        for (j = 0; j < SIZE; j++) {          

            // Initialize result cell
            result[i][j] = 0;                 

            // Multiply row × column
            for (k = 0; k < SIZE; k++) {
                
                // Dot product logic
                result[i][j] += a[i][k] * b[k][j];  
            }
        }
    }

    // Display result matrix
    printf("Resultant matrix:\n");
    for (i = 0; i < SIZE; i++) {
        for (j = 0; j < SIZE; j++) {
            
            // Print each element
            printf("%d ", result[i][j]);      
        }
        
        // New line after each row
        printf("\n");                         
    }

    return 0;   
}

Output:

Enter elements of the first 3x3 matrix:
1 2 3
4 5 6
7 8 9
Enter elements of the second 3x3 matrix:
9 8 7
6 5 4
3 2 1
Resultant matrix:
30 24 18
84 69 54
138 114 90

Explanation:

The simplest method for matrix multiplication in C involves using three nested loops. The outer loop iterates over rows of the first matrix, the middle loop over columns of the second matrix, and the innermost loop computes the dot product of the corresponding row and column. 

This C program for matrix multiplication works best for small-sized matrices. It uses arrays to store and process data, making it easy to understand and implement.

Time Complexity Analysis

Time Complexity : O(n³)

Space Complexity Analysis

Space Complexity : O(n²)

Option 2: C Program to Multiply Two Matrices Using Functions

#include <stdio.h>
#define SIZE 2   

// Function to take matrix input
void inputMatrix(int mat[SIZE][SIZE]) {

    // Loop rows
    for (int i = 0; i < SIZE; i++) {
        
        // Loop columns
        for (int j = 0; j < SIZE; j++) {
            
            // Store input
            scanf("%d", &mat[i][j]);          
        }
    }
}

// Function to multiply matrices
void multiply(int a[SIZE][SIZE], int b[SIZE][SIZE], int result[SIZE][SIZE]) {

    // Rows of first matrix
    for (int i = 0; i < SIZE; i++) {
        
        // Columns of second matrix
        for (int j = 0; j < SIZE; j++) {      

            // Initialize result
            result[i][j] = 0;                 

            // Dot product calculation
            for (int k = 0; k < SIZE; k++) {  
                result[i][j] += a[i][k] * b[k][j];
            }
        }
    }
}

// Function to print matrix
void display(int mat[SIZE][SIZE]) {

    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            
            // Print element
            printf("%d ", mat[i][j]);         
        }
        
        // Next row
        printf("\n");                         
    }
}

int main() {

    int a[SIZE][SIZE], b[SIZE][SIZE], result[SIZE][SIZE];

    printf("Enter first matrix:\n");
    inputMatrix(a);       

    printf("Enter second matrix:\n");
    inputMatrix(b);

    // Multiply matrices
    multiply(a, b, result);   

    printf("Result:\n");
    display(result);          

    return 0;
}

Output:

Enter elements of first matrix:
1 2
3 4
Enter elements of second matrix:
5 6
7 8
Resultant matrix:
19 22
43 50

Explanation:

This approach organizes the program by dividing tasks into functions for input, processing, and output. It enhances readability and reusability. 

A C program to multiply two matrices using this approach separates logic for clarity. Each function performs a specific role: taking inputs, multiplying matrices, or displaying the result.

Time Complexity Analysis

Time Complexity : O(n³)

Space Complexity Analysis

Space Complexity : O(n²)

Option 3: C Program for Multiplication of Two Matrices Using Pointers

#include <stdio.h>

#define SIZE 2

// Function using pointer arithmetic
void multiply(int *a, int *b, int *result) {

    // Row loop
    for (int i = 0; i < SIZE; i++) {
        
        // Column loop
        for (int j = 0; j < SIZE; j++) {          

            // Initialize element
            *(result + i * SIZE + j) = 0;

            // Dot product loop
            for (int k = 0; k < SIZE; k++) {      

                // Access elements using pointer arithmetic
                *(result + i * SIZE + j) +=
                    *(a + i * SIZE + k) * *(b + k * SIZE + j);
            }
        }
    }
}

int main() {

    int a[SIZE][SIZE] = {{1, 2}, {3, 4}};
    int b[SIZE][SIZE] = {{5, 6}, {7, 8}};
    int result[SIZE][SIZE];

    // Pass as pointer
    multiply((int *)a, (int *)b, (int *)result);   

    // Print result matrix
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output:

Resultant matrix:
19 22
43 50

Explanation:

The C program for matrix multiplication using pointers is more efficient as it directly accesses memory locations. Instead of using array indices, pointers calculate the product of matrices. 

This approach is particularly useful for understanding memory manipulation and enhancing performance in some scenarios.

Time Complexity Analysis

Time Complexity : O(n³)

Space Complexity Analysis

Space Complexity : O(n²)

Option 4: Matrix multiplication in C Using Dynamic Memory Allocation

#include <stdio.h>
#include <stdlib.h>

// Function to multiply two matrices
void multiplyMatrices(int **a, int **b, int **result, int r1, int c1, int c2) {

    // Loop through rows of first matrix
    for (int i = 0; i < r1; i++) {

        // Loop through columns of second matrix
        for (int j = 0; j < c2; j++) {

            result[i][j] = 0;   // Initialize result cell

            // Perform dot product of row and column
            for (int k = 0; k < c1; k++) {
                
                // Multiply and accumulate
                result[i][j] += a[i][k] * b[k][j];  
            }
        }
    }
}

int main() {

    int r1, c1, r2, c2;

    // Take dimensions of first matrix
    printf("Enter rows and columns of first matrix: ");
    scanf("%d %d", &r1, &c1);

    // Take dimensions of second matrix
    printf("Enter rows and columns of second matrix: ");
    scanf("%d %d", &r2, &c2);

    // Check if multiplication is possible
    // Condition: columns of first matrix == rows of second matrix
    if (c1 != r2) {
        printf("Matrix multiplication not possible.\n");
        return 0;   // Exit program if condition fails
    }

    // Dynamically allocate memory for matrices
    // First matrix
    int **a = (int **)malloc(r1 * sizeof(int *));
    
    // Second matrix
    int **b = (int **)malloc(r2 * sizeof(int *));
    
    // Result matrix
    int **result = (int **)malloc(r1 * sizeof(int *));  

    // Allocate memory for each row of first matrix
    for (int i = 0; i < r1; i++)
        a[i] = (int *)malloc(c1 * sizeof(int));

    // Allocate memory for each row of second matrix
    for (int i = 0; i < r2; i++)
        b[i] = (int *)malloc(c2 * sizeof(int));

    // Allocate memory for each row of result matrix
    for (int i = 0; i < r1; i++)
        result[i] = (int *)malloc(c2 * sizeof(int));

    // Input elements of first matrix
    printf("Enter elements of first matrix:\n");
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c1; j++) {
            scanf("%d", &a[i][j]);   // Store value in matrix
        }
    }

    // Input elements of second matrix
    printf("Enter elements of second matrix:\n");
    for (int i = 0; i < r2; i++) {
        for (int j = 0; j < c2; j++) {
            
            // Store value in matrix
            scanf("%d", &b[i][j]);   
        }
    }

    // Call function to multiply matrices
    multiplyMatrices(a, b, result, r1, c1, c2);

    // Display the result matrix
    printf("Resultant matrix:\n");
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            
            // Print each element
            printf("%d ", result[i][j]);  
        }
        
        // Move to next row
        printf("\n");  
    }

    // Free allocated memory (important to avoid memory leaks)
    // Free first matrix
    for (int i = 0; i < r1; i++)
        free(a[i]);

    // Free second matrix
    for (int i = 0; i < r2; i++)
        free(b[i]);

    // Free result matrix
    for (int i = 0; i < r1; i++)
        free(result[i]);

    // Free base pointers
    free(a);
    free(b);
    free(result);

    return 0;   
}

Output:

Enter rows and columns of first matrix: 2 3
Enter rows and columns of second matrix: 3 2
Enter elements of first matrix:
1 2 3
4 5 6
Enter elements of second matrix:
7 8
9 10
11 12
Resultant matrix:
58 64
139 154

Explanation:

Dynamic memory allocation is helpful when the size of matrices is unknown during compile time. This program for matrix multiplication in C uses malloc to allocate memory dynamically, making it flexible and efficient for handling large matrices. 

After processing, memory is freed to avoid leaks. This approach is essential for scalable applications.

Time Complexity Analysis

Time Complexity : O(n³)

Space Complexity Analysis

Space Complexity : O(n²)

Option 5: Optimized Block Multiplication of Matrices in C

#include <stdio.h>
#define BLOCK_SIZE 2   

// Function to multiply two block matrices
void multiplyBlock(int a[BLOCK_SIZE][BLOCK_SIZE], 
                   int b[BLOCK_SIZE][BLOCK_SIZE], 
                   int c[BLOCK_SIZE][BLOCK_SIZE]) {

    // Loop through rows of first matrix
    for (int i = 0; i < BLOCK_SIZE; i++) {

        // Loop through columns of second matrix
        for (int j = 0; j < BLOCK_SIZE; j++) {

            // Loop for dot product calculation
            for (int k = 0; k < BLOCK_SIZE; k++) {

                // Multiply corresponding elements and 
                // accumulate result
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }
}

int main() {

    // Initialize first matrix (block)
    int a[BLOCK_SIZE][BLOCK_SIZE] = {{1, 2}, {3, 4}};

    // Initialize second matrix (block)
    int b[BLOCK_SIZE][BLOCK_SIZE] = {{5, 6}, {7, 8}};

    // Initialize result matrix with 0
    int c[BLOCK_SIZE][BLOCK_SIZE] = {{0, 0}, {0, 0}};

    // Call function to multiply matrices
    multiplyBlock(a, b, c);

    // Display the resultant matrix
    printf("Resultant block matrix:\n");

    for (int i = 0; i < BLOCK_SIZE; i++) {      
        for (int j = 0; j < BLOCK_SIZE; j++) {    
            printf("%d ", c[i][j]);          
        }
        printf("\n");  
    }

    return 0;  
}

Output:

Resultant block matrix:
19 22
43 50

Explanation:

For large matrices, block multiplication divides matrices into smaller blocks (submatrices) to optimize memory usage and improve cache performance. This C program for matrix multiplication using arrays is widely used in high-performance computing.

Time Complexity Analysis

Time Complexity : O(n³)

Space Complexity Analysis

Space Complexity : O(n²)

Option 6: Sparse Matrix Multiplication in C

#include <stdio.h>

// Function to multiply two sparse matrices
void multiplySparseMatrices(int rows1, int cols1, int rows2, int cols2,
                            int sparse1[][3], int sparse2[][3], int result[][3]) {

    // Counter for result elements
    int k = 0;   

    // Traverse non-zero elements of first sparse matrix
    for (int i = 1; i <= sparse1[0][2]; i++) {

        // Traverse non-zero elements of second sparse matrix
        for (int j = 1; j <= sparse2[0][2]; j++) {

            // Check if column of first matches row of second
            if (sparse1[i][1] == sparse2[j][0]) {

                k++;  // Move to next result position

                // Store row index of result element
                result[k][0] = sparse1[i][0];

                // Store column index of result element
                result[k][1] = sparse2[j][1];

                // Multiply values and store result
                result[k][2] = sparse1[i][2] * sparse2[j][2];
            }
        }
    }

    // Store metadata (rows, columns, total non-zero elements)
    result[0][0] = rows1;
    result[0][1] = cols2;
    result[0][2] = k;
}

int main() {

    // Sparse matrix format: {row, column, value}
    // First row stores: total rows, total columns, number of non-zero elements
    int sparse1[4][3] = {
        {2, 3, 2},
        {0, 0, 5},   
        {1, 2, 8}   
    };

    int sparse2[4][3] = {
        {3, 2, 2},   
        {0, 1, 3},   
        {2, 1, 6} 
    };

    // Result sparse matrix
    int result[10][3] = {0};   

    // Call function to multiply sparse matrices
    multiplySparseMatrices(2, 3, 3, 2, sparse1, sparse2, result);

    // Display the resultant sparse matrix
    printf("Resultant sparse matrix:\n");

    // Loop through all non-zero elements 
    // (including metadata row)
    for (int i = 0; i <= result[0][2]; i++) {

        // Print row index, column index, and value
        printf("%d %d %d\n", result[i][0], result[i][1], result[i][2]);
    }

    return 0;
}

Output:

Resultant sparse matrix:
2 2 1

Explanation:

For matrices with mostly zero elements, sparse matrix multiplication optimizes computation by skipping zero values. This C program for matrix multiplication uses the compressed sparse row (CSR) format for efficient operations, reducing both memory usage and computation time.

Time Complexity Analysis

Time Complexity : O(n²)

Space Complexity Analysis

Space Complexity : O(n²)

Option 7: C Program to Multiply Two Matrices Using Recursion

#include <stdio.h>
#define SIZE 2   

// Recursive function to multiply matrices
void multiply(int a[SIZE][SIZE], int b[SIZE][SIZE], int result[SIZE][SIZE],
              int i, int j, int k) {

    // Base condition: if all rows are processed
    if (i >= SIZE)
        return;

    // If all columns for current row are processed, 
    // move to next row
    if (j >= SIZE) {
        multiply(a, b, result, i + 1, 0, 0);
        return;
    }

    // If k reaches SIZE, move to next column
    if (k >= SIZE) {
        multiply(a, b, result, i, j + 1, 0);
        return;
    }

    // Multiply and accumulate value (dot 
    // product logic)
    result[i][j] += a[i][k] * b[k][j];

    // Recursive call for next k
    multiply(a, b, result, i, j, k + 1);
}

int main() {

    // Input matrices
    int a[SIZE][SIZE] = {{1, 2}, {3, 4}};
    int b[SIZE][SIZE] = {{5, 6}, {7, 8}};

    // Result matrix initialized to 0
    int result[SIZE][SIZE] = {0};

    // Start recursion from (0,0,0)
    multiply(a, b, result, 0, 0, 0);

    printf("Resultant matrix:\n");

    for (int i = 0; i < SIZE; i++) {          
        for (int j = 0; j < SIZE; j++) {
            printf("%d ", result[i][j]);     
        }
        printf("\n");
    }

    return 0;   
}

Output:

Resultant matrix:
19 22 
43 50

Explanation:

  • The program uses a recursive function multiply() to perform matrix multiplication by simulating three nested loops using parameters i (row), j (column), and k (element index).

  • Base conditions control the recursion flow: when all elements in a row or column are processed, it moves to the next column or row, ensuring every position in the result matrix is computed.

  • For each position result[i][j], it calculates the value using dot product logic (a[i][k] * b[k][j]) and accumulates the result, then prints the final matrix in main().

Time Complexity Analysis

Time Complexity : O(n³)

Space Complexity Analysis

Space Complexity : O(n²)

Comparison of Matrix Multiplication Programs in C

MethodSimplicityMemory EfficiencyPerformanceBest Use Case
Basic Nested LoopsHighLowModerateSmall matrices
FunctionsModerateLowModerateModular programs
Dynamic Memory AllocationLowHighModerateLarge or dynamic-sized matrices
Pointer-BasedLowModerateHighPerformance-critical programs
Block MultiplicationLowModerateHighLarge matrices
Sparse Matrix MultiplicationModerateHighVery HighSparse matrix scenarios
RecursionLowLowLowConcept learning, recursion practice


No comments:

Post a Comment