Multiply Two Matrices in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Multiply Two Matrices in C: Program for Matrix Multiplication

šŸ“‘ On this page:
  • Introduction
  • C Program to Multiply Two Matrices
  • Sample Output
  • Program Explanation
  • Algorithm
  • Practice Exercise
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • What is matrix multiplication and when it is possible
  • How to multiply two matrices using nested loops
  • The condition for matrix multiplication (columns of A = rows of B)
  • Step-by-step explanation of the program
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to multiply two matrices.

Matrix multiplication is a binary operation that produces a matrix from two matrices. It is a fundamental operation in linear algebra and is used in many applications.

šŸ’” Key Point: Matrix multiplication is possible only when the number of columns of the first matrix equals the number of rows of the second matrix.

Matrix Multiplication Rule

  • Matrix A: Dimensions r1 Ɨ c1
  • Matrix B: Dimensions r2 Ɨ c2
  • Condition: c1 == r2 (columns of A = rows of B)
  • Result Matrix C: Dimensions r1 Ɨ c2

Formula:

C[i][j] = Ī£ (A[i][k] Ɨ B[k][j]) for k = 0 to (c1 - 1)

Each element of the result matrix is the dot product of a row from A and a column from B.

Visual Example

Matrix A (2Ɨ3):

[1  2  3]
[4  5  6]

Matrix B (3Ɨ2):

[7   8]
[9  10]
[11 12]

Result C (2Ɨ2):

[58  64]
[139 154]

Calculation: C[0][0] = 1Ɨ7 + 2Ɨ9 + 3Ɨ11 = 7 + 18 + 33 = 58
C[0][1] = 1Ɨ8 + 2Ɨ10 + 3Ɨ12 = 8 + 20 + 36 = 64
C[1][0] = 4Ɨ7 + 5Ɨ9 + 6Ɨ11 = 28 + 45 + 66 = 139
C[1][1] = 4Ɨ8 + 5Ɨ10 + 6Ɨ12 = 32 + 50 + 72 = 154

Matrix multiplication is used in many real-world applications, such as:

  • Computer Graphics: Transformations (rotation, scaling, translation)
  • Machine Learning: Neural networks and data transformations
  • Physics: Quantum mechanics and coordinate transformations
  • Economics: Input-output analysis

C Program to Multiply Two Matrices

#include <stdio.h>

int main() {
    int r1, c1, r2, c2, i, j, k;
    
    // ====== FIRST MATRIX ======
    printf("Enter the number of rows and columns of first matrix: ");
    scanf("%d %d", &r1, &c1);
    
    // ====== SECOND MATRIX ======
    printf("Enter the number of rows and columns of second matrix: ");
    scanf("%d %d", &r2, &c2);
    
    // Check if multiplication is possible
    if(c1 != r2) {
        printf("\nāŒ Matrix multiplication not possible!\n");
        printf("Number of columns of first matrix (%d) must equal number of rows of second matrix (%d).\n", c1, r2);
        return 1;
    }
    
    // Declare matrices
    int A[r1][c1], B[r2][c2], C[r1][c2];
    
    // ====== READ FIRST MATRIX ======
    printf("\nEnter %d elements for first matrix:\n", r1 * c1);
    for(i = 0; i < r1; i++) {
        for(j = 0; j < c1; j++) {
            printf("A[%d][%d] = ", i, j);
            scanf("%d", &A[i][j]);
        }
    }
    
    // ====== READ SECOND MATRIX ======
    printf("\nEnter %d elements for second matrix:\n", r2 * c2);
    for(i = 0; i < r2; i++) {
        for(j = 0; j < c2; j++) {
            printf("B[%d][%d] = ", i, j);
            scanf("%d", &B[i][j]);
        }
    }
    
    // ====== MATRIX MULTIPLICATION ======
    // Initialize result matrix with 0
    for(i = 0; i < r1; i++) {
        for(j = 0; j < c2; j++) {
            C[i][j] = 0;
        }
    }
    
    // Multiply A and B
    for(i = 0; i < r1; i++) {
        for(j = 0; j < c2; j++) {
            for(k = 0; k < c1; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
    
    // ====== DISPLAY MATRICES ======
    printf("\n=== First Matrix (%dƗ%d) ===\n", r1, c1);
    for(i = 0; i < r1; i++) {
        for(j = 0; j < c1; j++) {
            printf("%d\t", A[i][j]);
        }
        printf("\n");
    }
    
    printf("\n=== Second Matrix (%dƗ%d) ===\n", r2, c2);
    for(i = 0; i < r2; i++) {
        for(j = 0; j < c2; j++) {
            printf("%d\t", B[i][j]);
        }
        printf("\n");
    }
    
    printf("\n=== Result Matrix (%dƗ%d) ===\n", r1, c2);
    for(i = 0; i < r1; i++) {
        for(j = 0; j < c2; j++) {
            printf("%d\t", C[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}

Sample Output

Enter the number of rows and columns of first matrix: 2 3
Enter the number of rows and columns of second matrix: 3 2

Enter 6 elements for first matrix:
A[0][0] = 1
A[0][1] = 2
A[0][2] = 3
A[1][0] = 4
A[1][1] = 5
A[1][2] = 6

Enter 6 elements for second matrix:
B[0][0] = 7
B[0][1] = 8
B[1][0] = 9
B[1][1] = 10
B[2][0] = 11
B[2][1] = 12

=== First Matrix (2Ɨ3) ===
1	2	3
4	5	6

=== Second Matrix (3Ɨ2) ===
7	8
9	10
11	12

=== Result Matrix (2Ɨ2) ===
58	64
139	154

Square Matrix Example:

Enter the number of rows and columns of first matrix: 3 3
Enter the number of rows and columns of second matrix: 3 3

Enter 9 elements for first matrix:
A[0][0] = 1
A[0][1] = 2
A[0][2] = 3
A[1][0] = 4
A[1][1] = 5
A[1][2] = 6
A[2][0] = 7
A[2][1] = 8
A[2][2] = 9

Enter 9 elements for second matrix:
B[0][0] = 9
B[0][1] = 8
B[0][2] = 7
B[1][0] = 6
B[1][1] = 5
B[1][2] = 4
B[2][0] = 3
B[2][1] = 2
B[2][2] = 1

=== First Matrix (3Ɨ3) ===
1	2	3
4	5	6
7	8	9

=== Second Matrix (3Ɨ3) ===
9	8	7
6	5	4
3	2	1

=== Result Matrix (3Ɨ3) ===
30	24	18
84	69	54
138	114	90

When Multiplication is Not Possible:

Enter the number of rows and columns of first matrix: 2 3
Enter the number of rows and columns of second matrix: 4 2

āŒ Matrix multiplication not possible!
Number of columns of first matrix (3) must equal number of rows of second matrix (4).

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int r1, c1; — dimensions of first matrix
    • int r2, c2; — dimensions of second matrix
    • int i, j, k; — loop counters
  3. Check Multiplication Condition: If c1 != r2, the matrices cannot be multiplied. Display an error message and exit.
  4. Read Matrices: Reads elements into both matrices.
  5. Initialize Result Matrix: Sets all elements of C to 0.
  6. Matrix Multiplication (Triple Nested Loop):
    • Outer Loop (i): Iterates through rows of A
    • Middle Loop (j): Iterates through columns of B
    • Inner Loop (k): Iterates through the common dimension (columns of A / rows of B)
    • C[i][j] += A[i][k] * B[k][j] — calculates the dot product
  7. Display Results: Prints all three matrices.
  8. Return: return 0; indicates successful program execution.

šŸ“ Note: The order of multiplication matters. A Ɨ B is not the same as B Ɨ A in most cases. Matrix multiplication is not commutative.

Algorithm for Matrix Multiplication

Step-by-step algorithm:

  1. Start
  2. Read dimensions of first matrix (r1, c1)
  3. Read dimensions of second matrix (r2, c2)
  4. If c1 != r2:
    • Print "Multiplication not possible"
    • Exit
  5. Read elements of first matrix (A)
  6. Read elements of second matrix (B)
  7. Create result matrix C of size r1 Ɨ c2
  8. For i = 0 to r1-1:
    • For j = 0 to c2-1:
      • Set C[i][j] = 0
      • For k = 0 to c1-1:
        • C[i][j] += A[i][k] * B[k][j]
  9. Print the result matrix
  10. End

Visualizing Matrix Multiplication

For C[i][j], we take the ith row of A and the jth column of B:

A: [a11  a12  a13]     B: [b11  b12]     C: [c11  c12]
    [a21  a22  a23]         [b21  b22]         [c21  c22]
                            [b31  b32]

c11 = a11*b11 + a12*b21 + a13*b31
c12 = a11*b12 + a12*b22 + a13*b32
c21 = a21*b11 + a22*b21 + a23*b31
c22 = a21*b12 + a22*b22 + a23*b32

Time and Space Complexity

Operation Time Complexity Space Complexity
Reading Matrices O(r1Ɨc1 + r2Ɨc2) O(1)
Matrix Multiplication O(r1 Ɨ c2 Ɨ c1) O(1)
Overall O(r1 Ɨ c1 Ɨ c2) O(r1 Ɨ c2)

šŸ’» Practice Exercise

Challenge 1: Write a program to multiply two matrices using functions (create a function for matrix multiplication).

Challenge 2: Multiply a matrix by a scalar value (multiply every element by a number).

šŸ” Click to Show Solution for Challenge 1
#include <stdio.h>

void multiplyMatrices(int A[][10], int B[][10], int C[][10], int r1, int c1, int c2) {
    int i, j, k;
    for(i = 0; i < r1; i++) {
        for(j = 0; j < c2; j++) {
            C[i][j] = 0;
            for(k = 0; k < c1; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
}

void displayMatrix(int matrix[][10], int rows, int cols) {
    int i, j;
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int r1, c1, r2, c2;
    
    printf("Enter rows and columns of first matrix: ");
    scanf("%d %d", &r1, &c1);
    printf("Enter rows and columns of second matrix: ");
    scanf("%d %d", &r2, &c2);
    
    if(c1 != r2) {
        printf("Multiplication not possible!\n");
        return 1;
    }
    
    int A[10][10], B[10][10], C[10][10];
    
    // Read matrices (code omitted for brevity)
    // ... read A and B
    
    multiplyMatrices(A, B, C, r1, c1, c2);
    
    printf("\nResult Matrix:\n");
    displayMatrix(C, r1, c2);
    
    return 0;
}

Frequently Asked Questions

1. What is the condition for matrix multiplication?

The number of columns of the first matrix must equal the number of rows of the second matrix. If A is m Ɨ n and B is n Ɨ p, then multiplication is possible.

2. What is the result of multiplying two matrices?

If A is m Ɨ n and B is n Ɨ p, the result matrix C has dimensions m Ɨ p. Each element C[i][j] is the dot product of row i of A and column j of B.

3. Is matrix multiplication commutative?

No, matrix multiplication is not commutative. A Ɨ B is not equal to B Ɨ A in most cases. The order matters.

4. What is the time complexity of matrix multiplication?

The standard matrix multiplication algorithm has a time complexity of O(m Ɨ n Ɨ p), where m and p are the dimensions of the result and n is the common dimension.

5. Can I multiply a matrix by a scalar?

Yes, scalar multiplication is different from matrix multiplication. To multiply a matrix by a scalar, you multiply each element of the matrix by the scalar value.

šŸ’” Tip: Matrix multiplication is associative (AƗ(BƗC) = (AƗB)ƗC) and distributive (AƗ(B+C) = AƗB + AƗC).

šŸ“– Related Tutorials

  • Transpose a Matrix in C
  • Matrix Addition in C
  • Matrix Subtraction in C
  • More Array Assignments

Previous Topic: -->> Transpose a Matrix in C   ||   Next topic: -->> Matrix Addition in C


šŸ“š Explore More Topics

šŸ—„ļø SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

šŸ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

ā˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.