Search code examples
vb6magic-square

Magic square error in visual basic 6.0


I'm developing a program in visual basic 6.0 to display magic square. I've developed the logic, but the values are not getting displayed in the magic square. Here's the code :

Private Sub Command1_Click()
  Dim limit As Integer
  Dim a(100, 100) As Integer
  limit = InputBox("Enter the limit")
  If limit Mod 2 = 0 Then ' Rows and columns must be
    MsgBox "Can't be done", vbOKCancel, "Error"
  Else ' set number of rows and columns to limit
    mfgsquare.Rows = limit
    mfgsquare.Cols = limit
    j = (n + 1) / 2
    i = 1
    For c = 1 To n * n
      mfgsquare.TextMatrix(i, j) = c
      If c Mod n = 0 Then
        i = i + 1
        GoTo label
      End If
      If i = 1 Then
        i = n
      Else
        i = i - 1
      End If
      If j = n Then
        j = 1
      Else
        j = j + 1
      End If
label:
    Next c
  End If
End Sub

Solution

  • Try this:

      n = InputBox("Enter the limit")
      If n Mod 2 = 0 Then ' Rows and columns must be
        MsgBox "Can't be done"
      Else ' set number of rows and columns to limit
        mfgsquare.Rows = n + 1
        mfgsquare.Cols = n + 1
        For i = 1 To n
            For j = 1 To n
                mfgsquare.TextMatrix(i, j) = n * ((i + j - 1 + Int(n / 2)) Mod n) + ((i + 2 * j - 2) Mod n) + 1
            Next j
        Next i
      End If