# C# program to add two matrices

CsharpProgrammingServer Side Programming

#### CSharp Online Training

59 Lectures 6.5 hours

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:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
arr1[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.Write("Enter elements in the second matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
arr2[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.Write("\nFirst matrix is:\n");
for (i = 0; i < n; i++) {
Console.Write("\n");
for (j = 0; j < n; j++)
Console.Write("{0}\t", arr1[i, j]);
}
Console.Write("\nSecond matrix is:\n");
for (i = 0; i < n; i++) {
Console.Write("\n");
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];
Console.Write("\nAdding two matrices: \n");
for (i = 0; i < n; i++) {
Console.Write("\n");
for (j = 0; j < n; j++)
Console.Write("{0}\t", arr3[i, j]);
}
Console.Write("\n\n");
}
}

## 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