Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to perform Matrix Addition using C#?
Matrix addition in C# involves adding corresponding elements from two matrices of the same dimensions. The matrices must have identical rows and columns for addition to be possible. The result is a new matrix where each element is the sum of the corresponding elements from the input matrices.
Syntax
Following is the basic syntax for matrix addition −
int[,] result = new int[rows, columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i, j] = matrix1[i, j] + matrix2[i, j];
}
}
Matrix Addition Visualization
Using Fixed Matrix Values
Here's an example with predefined matrix values to demonstrate the addition process −
using System;
class MatrixAddition {
static void Main() {
int rows = 3, cols = 3;
// Initialize first matrix
int[,] matrix1 = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
// Initialize second matrix
int[,] matrix2 = {{9, 8, 7},
{6, 5, 4},
{3, 2, 1}};
// Result matrix
int[,] result = new int[rows, cols];
// Perform matrix addition
for (int i = 0; i
The output of the above code is −
Matrix 1:
1 2 3
4 5 6
7 8 9
Matrix 2:
9 8 7
6 5 4
3 2 1
Result (Matrix 1 + Matrix 2):
10 10 10
10 10 10
10 10 10
Using a Method for Matrix Addition
Here's a more structured approach using a dedicated method for matrix addition −
using System;
class MatrixOperations {
static void Main() {
int[,] matrixA = {{2, 4, 6}, {1, 3, 5}};
int[,] matrixB = {{1, 2, 3}, {4, 5, 6}};
int[,] sum = AddMatrices(matrixA, matrixB);
Console.WriteLine("Matrix A:");
PrintMatrix(matrixA);
Console.WriteLine("Matrix B:");
PrintMatrix(matrixB);
Console.WriteLine("Sum (A + B):");
PrintMatrix(sum);
}
static int[,] AddMatrices(int[,] matrix1, int[,] matrix2) {
int rows = matrix1.GetLength(0);
int cols = matrix1.GetLength(1);
int[,] result = new int[rows, cols];
for (int i = 0; i
The output of the above code is −
Matrix A:
2 4 6
1 3 5
Matrix B:
1 2 3
4 5 6
Sum (A + B):
3 6 9
5 8 11
Key Rules
-
Both matrices must have the same dimensions (same number of rows and columns).
-
Addition is performed element-wise:
C[i,j] = A[i,j] + B[i,j]. -
Matrix addition is commutative: A + B = B + A.
-
Use
GetLength(0)for rows andGetLength(1)for columns when working with dynamic matrices.
Conclusion
Matrix addition in C# is straightforward using nested loops to iterate through corresponding elements. The key requirement is that both matrices must have identical dimensions, and the operation follows the simple rule of adding corresponding elements to produce the result matrix.
