I have a doubt, the program tries to add all the elements of the 4x4 matrix, I already have progress but the problem is that it does not add all the elements, only the rows and it gives me those 4 results and it only has to be 1 result of all the matrix, what am I doing wrong?
Public Class Form1
Dim matriz1(4, 4) As Integer
Dim Suma As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i = 1 To 4
For j = 1 To 4
matriz1(i, j) = InputBox("Ingresa un numero para la matriz 1", "numero", 0)
Next
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label1.Text = ""
Label2.Text = ""
For i = 1 To 4
Suma = 0
For j = 1 To 4
Label1.Text = Label1.Text & matriz1(i, j) & " "
Suma = Suma + matriz1(i, j)
Next
Label1.Text = Label1.Text & vbCrLf
Label2.Text = Label2.Text & Suma & " "
Next
End Sub
End Class
If you don't assign 0 to
Suma
every time you incrementi
, it's going to keep the sum of all elements.Thus, it has to be initialized to zero only once. If you do it inside the For loop of i, it's going to be zero for each row.
The same, if you want a single value, you have to paint it only once, outside the For of the rows. It doesn't make sense for you to move things inside the loop of j because you're going to paint or do things for each individual element in the array.
The key here is that you understand that what you put between For and Next happens as many times as there are iterations.