- Sum
- 4 nested cells
Perform Matrix Addition in C#
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;,staticmethods,Console.Write/WriteLine.- Know that
matrix[i, j]uses row indexithen column indexj.
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.
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.
Top-left of the reference matrices: 1 + 9 = 10.
Quick examples
- 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.
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
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 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.
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 addition with dimension check
Smaller matrices for beginners, plus SameDimensions so mismatched sizes fail fast with a clear message.
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
🔄 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) | 9 | 10 |
5 (center 3×3) | 5 | 10 |
1 (2×2) | 5 | 6 |
4 (2×2) | 8 | 12 |
Edge cases and pitfalls
Most bugs come from dimension mismatches or confusing row/column indices.
Mismatched dimensions
Always verify row and column counts match before allocating result.
[i, j] order
GetLength(0) is rows, GetLength(1) is columns — do not swap them in the loop bounds.
Single cell
Still valid — one iteration of each loop adds the only element.
vs multiplication
Do not use the addition loop for matrix product — different inner dimension logic.
⏱️ Time and space complexity
| Operation | Time | Extra space |
|---|---|---|
Add m × n matrices | O(m × n) | O(m × n) for result |
DisplayMatrix | O(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[,], nestedforloops,GetLengthfor bounds. - Helpers:
AddMatrices+DisplayMatrix; validate dimensions first.
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.
5 people found this page helpful
