Home »
VB.Net »
VB.Net Programs
VB.Net program to add two matrices
By Nidhi Last Updated : October 13, 2024
Add two matrices
Here, we will read two matrices from the user then add both matrices and assigned them to another matrix. After that, we will all matrices on the console screen.
Program/Source Code:
The source code to add two matrices is given below. The given program is compiled and executed successfully.
VB.Net code to add two matrices
'VB.Net program to add two matrices.
Module Module1
Sub Main()
Dim matrix1(,) As Integer = New Integer(2, 2) {}
Dim matrix2(,) As Integer = New Integer(2, 2) {}
Dim matrix3(,) As Integer = New Integer(2, 2) {}
Console.WriteLine("Enter Matrix1: ")
For i = 0 To 1 Step 1
For j = 0 To 1 Step 1
Console.Write("Enter element[{0}][{1}]: ", i, j)
matrix1(i, j) = Integer.Parse(Console.ReadLine())
Next
Next
Console.WriteLine("Enter Matrix2: ")
For i = 0 To 1 Step 1
For j = 0 To 1 Step 1
Console.Write("Enter element[{0}][{1}]: ", i, j)
matrix2(i, j) = Integer.Parse(Console.ReadLine())
Next
Next
'Add Matrix1 and Matrix2
For i = 0 To 1 Step 1
For j = 0 To 1 Step 1
matrix3(i, j) = matrix1(i, j) + matrix2(i, j)
Next
Next
Console.WriteLine("Matrix1: ")
For i = 0 To 1 Step 1
For j = 0 To 1 Step 1
Console.Write("{0} ", matrix1(i, j))
Next
Console.WriteLine()
Next
Console.WriteLine("Matrix2: ")
For i = 0 To 1 Step 1
For j = 0 To 1 Step 1
Console.Write("{0} ", matrix2(i, j))
Next
Console.WriteLine()
Next
Console.WriteLine("Addition of Matrix1 and Matrix2: ")
For i = 0 To 1 Step 1
For j = 0 To 1 Step 1
Console.Write("{0} ", matrix3(i, j))
Next
Console.WriteLine()
Next
End Sub
End Module
Output
Enter Matrix1:
Enter element[0][0]: 10
Enter element[0][1]: 20
Enter element[1][0]: 30
Enter element[1][1]: 40
Enter Matrix2:
Enter element[0][0]: 20
Enter element[0][1]: 30
Enter element[1][0]: 40
Enter element[1][1]: 50
Matrix1:
10 20
30 40
Matrix2:
20 30
40 50
Addition of Matrix1 and Matrix2:
30 50
70 90
Press any key to continue . . .
Explanation
In the above program, we created a module Module1 that contains a function Main(). In the Main(), we created three matrices of 2x2 using a two-dimensional array.
Console.WriteLine("Enter Matrix1: ")
For i = 0 To 1 Step 1
For j = 0 To 1 Step 1
Console.Write("Enter element[{0}][{1}]: ", i, j)
matrix1(i, j) = Integer.Parse(Console.ReadLine())
Next
Next
Console.WriteLine("Enter Matrix2: ")
For i = 0 To 1 Step 1
For j = 0 To 1 Step 1
Console.Write("Enter element[{0}][{1}]: ", i, j)
matrix2(i, j) = Integer.Parse(Console.ReadLine())
Next
Next
In the above code, we read elements for both matrices from the user.
'Add Matrix1 and Matrix2
For i = 0 To 1 Step 1
For j = 0 To 1 Step 1
matrix3(i, j) = matrix1(i, j) + matrix2(i, j)
Next
Next
Here, in the above code, we add matrix1 and matrix2 and assigned the addition of both matrices into matrix3. After that, we printed the all matrices on the console screen.
VB.Net Array Programs »