adspace


write a C# Program add two matrix ?

Answer Posted / Alok Mehta

Here's an example of a simple console application that adds two matrices in C#:

```csharp
using System;

namespace MatrixAddition
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the number of rows for both matrices: ");
int rows = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the number of columns for both matrices: ");
int cols = Convert.ToInt32(Console.ReadLine());

if (rows != cols)
{
Console.WriteLine("Error! Matrices cannot be added as they have different dimensions.");
return;
}

int[,] matrix1 = new int[rows, cols];
int[,] matrix2 = new int[rows, cols];
int[,] resultMatrix = new int[rows, cols];

Console.WriteLine("Enter elements of first matrix:");
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix1[i, j] = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter elements of second matrix:");
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix2[i, j] = Convert.ToInt32(Console.ReadLine());

for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
resultMatrix[i, j] = matrix1[i, j] + matrix2[i, j];

Console.WriteLine("Result Matrix:");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
Console.Write(resultMatrix[i, j] + " ");
Console.WriteLine();
}
}
}
}
```

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Why can't we use a static class instead of singleton?

954


How to assign Null value to Var?

1064


What is expression tree in c#?

998


Which namespaces are necessary to create a localized application?

1142


How do you inherit a class into other class in c#?

995


What is an abstract class c#?

969