Write a program in C# to add and multiply two matrices of order nxn.
Following is the simple C# code :
Following is the simple C# code :
class Lab { static void Main(string[] args) { int i, j, rows, cols; Console.WriteLine("Enter the Number of Rows and Columns : "); rows = Convert.ToInt32(Console.ReadLine()); cols = Convert.ToInt32(Console.ReadLine()); int[,] FirstMatrix = new int[rows, cols]; Console.WriteLine("Enter the First Matrix"); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { FirstMatrix[i, j] = Convert.ToInt32(Console.ReadLine()); } } Console.WriteLine("First matrix is:"); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { Console.Write(FirstMatrix[i, j] + "\t"); } Console.WriteLine(); } int[,] SecondMatrix = new int[rows, cols]; Console.WriteLine("Enter the Second Matrix"); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { SecondMatrix[i, j] = Convert.ToInt32(Console.ReadLine()); } } Console.WriteLine("Second Matrix is :"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { Console.Write(SecondMatrix[i, j] + "\t"); } Console.WriteLine(); } Console.WriteLine("Matrix Multiplication is :"); int[,] MultiplicationMatrix = new int[rows, cols]; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { MultiplicationMatrix[i, j] = 0; for (int k = 0; k < 2; k++) { MultiplicationMatrix[i, j] += FirstMatrix[i, k] * SecondMatrix[k, j]; } } } for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { Console.Write(MultiplicationMatrix[i, j] + "\t"); } Console.WriteLine(); } Console.ReadKey(); } }
Output:-
Enter the Number of Rows and Columns : 2 2 Enter the First Matrix 4 5 6 7 First matrix is: 4 5 6 7 Enter the Second Matrix 4 7 9 6 Second Matrix is : 4 7 9 6 Matrix Multiplication is : 61 58 87 84
Multiplication is Possible if
No. of Columns of Matrix 1 = No of Columns of Matrix 2 Resultant Matrix Will of Dimension- c[No. of Rows of Matrix 1][No. of Columns of Matrix 2]
No comments:
Post a Comment
Note: only a member of this blog may post a comment.