
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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++) { arr1[i, j] = Convert.ToInt32(Console.ReadLine()); } } Console.Write("Enter elements in the second matrix:
"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { arr2[i, j] = Convert.ToInt32(Console.ReadLine()); } } 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]; Console.Write("
Adding two matrices:
"); 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 Adding two matrices: 000 000 000
Advertisements