Matrix Addition in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Matrix Addition in C: Program to Add Two Matrices

šŸ“‘ On this page:
  • Introduction
  • C Program for Matrix Addition
  • Sample Output
  • Program Explanation
  • Algorithm
  • Practice Exercise
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • What is matrix addition and its conditions
  • How to add two matrices using nested loops
  • How to handle matrices with different dimensions
  • 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 add two matrices.

Matrix addition is a simple operation where we add corresponding elements of two matrices. It is a fundamental operation in linear algebra and is used in many applications.

šŸ’” Key Point: Matrix addition is possible only when both matrices have the same dimensions (same number of rows and columns).

Matrix Addition Rule

  • Matrix A: Dimensions r Ɨ c
  • Matrix B: Dimensions r Ɨ c (must match)
  • Result Matrix C: Dimensions r Ɨ c
  • Formula: C[i][j] = A[i][j] + B[i][j]

Formula:

C[i][j] = A[i][j] + B[i][j]

Each element of the result matrix is the sum of corresponding elements from A and B.

Visual Example

Matrix A (2Ɨ3):

[1  2  3]
[4  5  6]

Matrix B (2Ɨ3):

[7   8   9]
[10  11  12]

Result C (2Ɨ3):

[8   10  12]
[14  16  18]

Calculation: C[0][0] = 1 + 7 = 8
C[0][1] = 2 + 8 = 10
C[0][2] = 3 + 9 = 12
C[1][0] = 4 + 10 = 14
C[1][1] = 5 + 11 = 16
C[1][2] = 6 + 12 = 18

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

  • Image Processing: Adding two images (overlay)
  • Data Analysis: Combining datasets
  • Physics: Adding vectors and matrices
  • Computer Graphics: Combining transformation matrices

C Program for Matrix Addition

#include <stdio.h>

int main() {
    int rows, cols, i, j;
    
    // Ask user for matrix dimensions
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    printf("Enter the number of columns: ");
    scanf("%d", &cols);
    
    // Declare matrices
    int A[rows][cols], B[rows][cols], C[rows][cols];
    
    // ====== READ FIRST MATRIX ======
    printf("\nEnter %d elements for first matrix:\n", rows * cols);
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            printf("A[%d][%d] = ", i, j);
            scanf("%d", &A[i][j]);
        }
    }
    
    // ====== READ SECOND MATRIX ======
    printf("\nEnter %d elements for second matrix:\n", rows * cols);
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            printf("B[%d][%d] = ", i, j);
            scanf("%d", &B[i][j]);
        }
    }
    
    // ====== MATRIX ADDITION ======
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }
    
    // ====== DISPLAY MATRICES ======
    printf("\n=== First Matrix (%dƗ%d) ===\n", rows, cols);
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            printf("%d\t", A[i][j]);
        }
        printf("\n");
    }
    
    printf("\n=== Second Matrix (%dƗ%d) ===\n", rows, cols);
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            printf("%d\t", B[i][j]);
        }
        printf("\n");
    }
    
    printf("\n=== Result Matrix (%dƗ%d) ===\n", rows, cols);
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            printf("%d\t", C[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}

Sample Output

Enter the number of rows: 2
Enter the number of columns: 3

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[0][2] = 9
B[1][0] = 10
B[1][1] = 11
B[1][2] = 12

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

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

=== Result Matrix (2Ɨ3) ===
8	10	12
14	16	18

Example with Square Matrices:

Enter the number of rows: 3
Enter the number of columns: 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) ===
10	10	10
10	10	10
10	10	10

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 rows, cols; — dimensions of the matrices
    • int i, j; — loop counters
  3. Declare Matrices:
    • int A[rows][cols]; — first matrix
    • int B[rows][cols]; — second matrix
    • int C[rows][cols]; — result matrix
  4. Read Matrices: Uses nested loops to read elements into both matrices.
  5. Matrix Addition: The nested loops add corresponding elements and store the result in C[i][j].
  6. Display Matrices: Prints all three matrices.
  7. Return: return 0; indicates successful program execution.

šŸ“ Note: The matrices must have the same dimensions for addition to work. If the dimensions differ, the program will not produce correct results.

Algorithm for Matrix Addition

Step-by-step algorithm:

  1. Start
  2. Read the number of rows and columns
  3. Read elements of first matrix (A)
  4. Read elements of second matrix (B)
  5. For i = 0 to rows-1:
    • For j = 0 to cols-1:
      • C[i][j] = A[i][j] + B[i][j]
  6. Print the result matrix
  7. End

Adding Matrices with Dimension Validation

A more robust program checks if the matrices have the same dimensions before performing addition:

#include <stdio.h>

int main() {
    int r1, c1, r2, c2, i, j;
    
    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);
    
    // Check if addition is possible
    if(r1 != r2 || c1 != c2) {
        printf("\nāŒ Matrix addition not possible!\n");
        printf("Both matrices must have the same dimensions.\n");
        return 1;
    }
    
    int A[r1][c1], B[r2][c2], C[r1][c1];
    
    // Read matrices (code omitted for brevity)
    // ... read A and B
    
    // Add matrices
    for(i = 0; i < r1; i++) {
        for(j = 0; j < c1; j++) {
            C[i][j] = A[i][j] + B[i][j];
        }
    }
    
    // Display result
    printf("\n=== Result Matrix ===\n");
    for(i = 0; i < r1; i++) {
        for(j = 0; j < c1; j++) {
            printf("%d\t", C[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}

Sample Output (Error Case):

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

āŒ Matrix addition not possible!
Both matrices must have the same dimensions.

Time and Space Complexity

Operation Time Complexity Space Complexity
Reading Matrices O(r Ɨ c) O(1)
Matrix Addition O(r Ɨ c) O(1)
Overall O(r Ɨ c) O(r Ɨ c)

šŸ’» Practice Exercise

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

Challenge 2: Add three matrices together.

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

void addMatrices(int A[][10], int B[][10], int C[][10], int rows, int cols) {
    int i, j;
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            C[i][j] = A[i][j] + B[i][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 rows, cols;
    
    printf("Enter rows and columns: ");
    scanf("%d %d", &rows, &cols);
    
    int A[10][10], B[10][10], C[10][10];
    
    printf("\nEnter elements of first matrix:\n");
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            scanf("%d", &A[i][j]);
        }
    }
    
    printf("\nEnter elements of second matrix:\n");
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            scanf("%d", &B[i][j]);
        }
    }
    
    addMatrices(A, B, C, rows, cols);
    
    printf("\nResult Matrix:\n");
    displayMatrix(C, rows, cols);
    
    return 0;
}

Frequently Asked Questions

1. What is the condition for matrix addition?

Both matrices must have the same dimensions (same number of rows and columns). If A is m Ɨ n, then B must also be m Ɨ n.

2. How do you add two matrices in C?

Use nested loops to iterate through each element and add corresponding elements: C[i][j] = A[i][j] + B[i][j].

3. What is the time complexity of matrix addition?

The time complexity is O(r Ɨ c), where r is the number of rows and c is the number of columns.

4. Is matrix addition commutative?

Yes, matrix addition is commutative. A + B = B + A. It is also associative: (A + B) + C = A + (B + C).

5. Can we add a matrix to itself?

Yes, adding a matrix to itself is the same as multiplying it by 2. For example, A + A = 2A.

šŸ’” Tip: Always check that the matrices have the same dimensions before performing addition. Otherwise, the operation is not defined.

šŸ“– Related Tutorials

  • Find Saddle Point in a Matrix
  • Matrix Subtraction in C
  • Matrix Multiplication in C
  • More Array Assignments

Previous Topic: -->> Find Saddle Point in a Matrix   ||   Next topic: -->> Matrix Subtraction 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.