Perform Matrix Addition in C#

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 2 Code Examples
2D arrays

What you’ll learn

  • What matrix addition means: add elements at the same row and column.
  • How to use int[,] rectangular arrays, GetLength(0) / GetLength(1), and nested loops.
  • Two programs: a 3×3 reference demo and a 2×2 version with a dimension check, plus a live 2×2 preview.

Overview

Matrix addition is the gateway to 2D array practice in C#. You walk every cell with nested loops, store sums in a new matrix, and print rows with an inner loop plus WriteLine after each row.

Two programs

3×3 full demo and 2×2 with size validation.

Live preview

Edit two 2×2 matrices and see the sum instantly.

Real uses

Graphics transforms, spreadsheets, scientific grids — same loop pattern.

Prerequisites

Nested for loops, 2D array syntax, and basic console output.

  • using System;, static methods, Console.Write / WriteLine.
  • Know that matrix[i, j] uses row index i then column index j.

What is matrix addition?

To add two matrices, add each pair of elements that share the same position: C[i,j] = A[i,j] + B[i,j].

Both matrices must have the same dimensions. A 3×3 plus another 3×3 works; mixing 2×3 with 3×2 does not.

C[i,j] A[i,j]+B[i,j]
Size must match
Order A+B = B+A

Element-wise sum

If A and B are both m × n, the sum C is m × n with Cij = Aij + Bij for every row i and column j.

Sample cell

Top-left of the reference matrices: 1 + 9 = 10.

Quick examples

2×2 Beginner
Sum
4 nested cells
3×3 Reference
Result
All cells become 10

Think row by row: print one row of values, then move to the next row — same order as reading a table left to right.

Live preview

Edit two 2×2 matrices. The widget adds matching cells and shows the result grid.

Matrix A

Matrix B

Default sum: [[6,8],[10,12]].

Live result
Press “Add matrices” to compute A + B.

Algorithm

Goal: compute C = A + B for equal-sized matrices.

Read dimensions

rows = A.GetLength(0), cols = A.GetLength(1). Confirm B matches.

Allocate result

int[,] result = new int[rows, cols];

Nested loops

For each (i, j): result[i,j] = A[i,j] + B[i,j].

📜 Pseudocode

Pseudocode
function addMatrices(A, B):
    assert same rows and columns
    rows ← row count of A
    cols ← column count of A
    C ← new matrix[rows][cols]
    for i from 0 to rows - 1:
        for j from 0 to cols - 1:
            C[i][j] ← A[i][j] + B[i][j]
    return C
1

3×3 matrix addition (reference)

Adds two fixed 3×3 matrices and prints both inputs plus the sum. Every cell in the result is 10 with the sample data.

c#
using System;

class Program
{
    static int[,] AddMatrices(int[,] mat1, int[,] mat2)
    {
        int rows = mat1.GetLength(0);
        int cols = mat1.GetLength(1);

        int[,] result = new int[rows, cols];

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                result[i, j] = mat1[i, j] + mat2[i, j];
            }
        }

        return result;
    }

    static void DisplayMatrix(int[,] matrix)
    {
        int rows = matrix.GetLength(0);
        int cols = matrix.GetLength(1);

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                Console.Write(matrix[i, j] + " ");
            }
            Console.WriteLine();
        }
    }

    static void Main()
    {
        int[,] matrix1 = {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 9 }
        };

        int[,] matrix2 = {
            { 9, 8, 7 },
            { 6, 5, 4 },
            { 3, 2, 1 }
        };

        int[,] resultMatrix = AddMatrices(matrix1, matrix2);

        Console.WriteLine("Matrix 1:");
        DisplayMatrix(matrix1);

        Console.WriteLine("\nMatrix 2:");
        DisplayMatrix(matrix2);

        Console.WriteLine("\nResultant Matrix:");
        DisplayMatrix(resultMatrix);
    }
}

Explanation

AddMatrices assumes both inputs share dimensions — fine for fixed literals in Main. DisplayMatrix uses Write inside the row loop and WriteLine after each row.

result[i, j] = mat1[i, j] + mat2[i, j];

Element-wise sum. Same indices on both sides — the core of matrix addition.

2

2×2 addition with dimension check

Smaller matrices for beginners, plus SameDimensions so mismatched sizes fail fast with a clear message.

c#
using System;

class Program
{
    static bool SameDimensions(int[,] a, int[,] b)
    {
        return a.GetLength(0) == b.GetLength(0)
            && a.GetLength(1) == b.GetLength(1);
    }

    static int[,] AddMatrices(int[,] mat1, int[,] mat2)
    {
        if (!SameDimensions(mat1, mat2))
        {
            throw new ArgumentException("Matrices must have the same dimensions.");
        }

        int rows = mat1.GetLength(0);
        int cols = mat1.GetLength(1);
        int[,] result = new int[rows, cols];

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                result[i, j] = mat1[i, j] + mat2[i, j];
            }
        }

        return result;
    }

    static void DisplayMatrix(int[,] matrix)
    {
        int rows = matrix.GetLength(0);
        int cols = matrix.GetLength(1);

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                Console.Write(matrix[i, j] + " ");
            }
            Console.WriteLine();
        }
    }

    static void Main()
    {
        int[,] matrix1 = {
            { 1, 2 },
            { 3, 4 }
        };

        int[,] matrix2 = {
            { 5, 6 },
            { 7, 8 }
        };

        int[,] sum = AddMatrices(matrix1, matrix2);

        Console.WriteLine("Sum:");
        DisplayMatrix(sum);
    }
}

Explanation

Matches the live preview defaults: 1+5=6, 2+6=8, 3+7=10, 4+8=12. In interviews, mention the dimension guard before writing the loops.

Beyond the basics

Jagged arrays. int[][] uses mat[i][j] and ragged rows — check each row length if sizes may differ.

double[,]. Same loops work for floating-point grids (sensor data, images).

Interview: state the size rule, draw a 2×2 example on paper, then write nested loops and a print helper.

❓ FAQ

Add corresponding elements from two matrices of the same size. Result[i,j] = A[i,j] + B[i,j].
No. Both matrices must have the same number of rows and columns.
For int[,] matrix: rows = matrix.GetLength(0), columns = matrix.GetLength(1).
Every cell becomes 10 because paired values sum to 10 (e.g. 1+9, 2+8, 3+7).
Yes. A + B equals B + A when dimensions match.
Nested for loops over row index i and column index j, visiting every cell once.
Addition adds matching cells. Multiplication uses dot products of rows and columns — a different, harder operation.

🔄 Input / output examples

Replace literal matrices in Main, or read dimensions and values from the console in your own extension.

A[i,j]B[i,j]Sum
1 (top-left 3×3)910
5 (center 3×3)510
1 (2×2)56
4 (2×2)812

Edge cases and pitfalls

Most bugs come from dimension mismatches or confusing row/column indices.

Size

Mismatched dimensions

Always verify row and column counts match before allocating result.

Index

[i, j] order

GetLength(0) is rows, GetLength(1) is columns — do not swap them in the loop bounds.

1×1

Single cell

Still valid — one iteration of each loop adds the only element.

Multiply

vs multiplication

Do not use the addition loop for matrix product — different inner dimension logic.

⏱️ Time and space complexity

OperationTimeExtra space
Add m × n matricesO(m × n)O(m × n) for result
DisplayMatrixO(m × n)O(1)

Every cell is visited once — optimal for a straightforward sum.

Summary

  • Rule: C[i,j] = A[i,j] + B[i,j] for equal-sized matrices.
  • C#: int[,], nested for loops, GetLength for bounds.
  • Helpers: AddMatrices + DisplayMatrix; validate dimensions first.
Did you know?

Matrix addition is element-wise: you add matching positions, not rows to columns. It is only defined when both matrices share the same number of rows and columns — a rule every 2D-array solution should validate before looping.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful