C# program to add two matrices

Firstly, set three arrays.

int[, ] arr1 = new int[20, 20];
int[, ] arr2 = new int[20, 20];
int[, ] arr3 = new int[20, 20];

Now users will enter values in both the matrices. We have to set the row and size columns as n=3, since we want a square matrix of 3x3 size i.e 9 elements.

Add both the matrices and print the third array that has the sum.

for(i=0;i<n;i++)
for(j=0;j<n;j++)
arr3[i,j]=arr1[i,j]+arr2[i,j];

The following is the complete code to add two matrices in C#.

Example

Live Demo

using System;
public class Exercise19 {
public static void Main() {
int i, j, n;
int[, ] arr1 = new int[20, 20];
int[, ] arr2 = new int[20, 20];
int[, ] arr3 = new int[20, 20];
// setting matrix row and columns size
n = 3;
Console.Write("Enter elements in the first matrix:");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
}
}
Console.Write("Enter elements in the second matrix:");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
}
}
Console.Write("First matrix is:");
for (i = 0; i < n; i++) {
Console.Write("");
for (j = 0; j < n; j++)
Console.Write("{0}\t", arr1[i, j]);
}
Console.Write("Second matrix is:");
for (i = 0; i < n; i++) {
Console.Write("");
for (j = 0; j < n; j++)
Console.Write("{0}\t", arr2[i, j]);
}
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
arr3[i, j] = arr1[i, j] + arr2[i, j];
for (i = 0; i < n; i++) {
Console.Write("");
for (j = 0; j < n; j++)
Console.Write("{0}\t", arr3[i, j]);
}
Console.Write("");
}
}

Output

Enter elements in the first matrix:
Enter elements in the second matrix:

First matrix is:

000
000
000
Second matrix is:

000
000
000
000