Sum of diagonal elements

Consider the matrix as shown below,
10 20 30
40 50 60
70 80 90
The elements whose row no. and column no. are equal
are called diagonal elements.The elements 10,50 and 90 are the
diagonal elements.
The code below shows how to add diagnal elements.


Private Sub MatrixDiagonalAddition()
Dim strArray As String = ""
'Create matrix M1.
Dim M1(3, 3) As Integer
Dim intValue As Integer = 10
Dim intI, intJ As Integer
Dim intSum As Integer

'intI represents row and
'intJ represents column of all the matrices.
'The intI in the for loop considers
'all the rows and intJ considers all
'the columns.So row is considered first
'and then the column, while performing
'every operation over matrix.

'Add data in matrix M1.
'Here the first element is 10 and
'then it is incremented by 10.
For intI = 0 To 2
For intJ = 0 To 2
M1(intI, intJ) = intValue
intValue = intValue + 10
Next
Next

'Display the matrix M1.
For intI = 0 To 2
For intJ = 0 To 2
If strArray.Length = 0 Then
strArray = " " & M1(intI, intJ)
Else
strArray = strArray & " " & M1(intI, intJ)
End If
Next
strArray = strArray & vbNewLine
Next
MessageBox.Show("The first matrix is " & vbNewLine & strArray)

'Addition of diagonal elements.
For intI = 0 To 2
For intJ = 0 To 2
If intI = intJ Then
'If the row no. and column no. are equal
'then save the sum in the variable intSum.
intSum = intSum + M1(intI, intJ)
End If
Next
Next
'Display the sum of diagonal elements.
MessageBox.Show(intSum)
End Sub


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: