Create magic square of the required size using the MSFlexgrid option in visual basic.

Friday, May 28, 2010

Procedure: First you know what mean magic square is. When ever you add column value and row value it is become the same value example if you give input as 5 then it will draw 5*5 matrixes it fill there 25 numeric value depends on the magic square logic . After fill the value you add column it is equal to 65 and when you add row it is equal to 65.
Output Screen shot of the magic squaremagic square required size using the MSFlexgrid option in visual basic.

17+24+1+8+15=65
23+5+7+14+16=65
Source CODE Visual Programming

Dim N As Integer
Private Sub MagicSquare()
Dim Row As Integer, Column As Integer, I As Integer, Number As Integer
Dim Magic(100, 100) As Integer
Number = 1
Row = 0
Column = (N + 1) / 2 - 1
Magic(Row, Column) = Number
For I = 2 To N * N
If Number Mod N <> 0 Then
Row = Row - 1
Column = Column + 1
Else
Row = Row + 1
End If
If Row < 0 Then Row = N - 1
If Column > N - 1 Then Column = 0
Number = Number + 1
Magic(Row, Column) = Number
Next I
'Loops to put the values into grid
For Row = 0 To N - 1
For Column = 0 To N - 1
MSFlexGrid1.Row = Row
MSFlexGrid1.Col = Column
MSFlexGrid1.Text = Format(Magic(Row, Column), "#####")
Next Column
Next Row
End Sub


Private Sub Form_Load()
Do While N Mod 2 = 0
N = Val(InputBox("Enter an Odd Number (Ex: 3, 5, 7 etc.)", _
"Order of Magic Square", 5))
Loop

MSFlexGrid1.Left = 0
MSFlexGrid1.Top = 0
MSFlexGrid1.Rows = N
MSFlexGrid1.Cols = N
Call MagicSquare
End Sub

Private Sub Form_Resize()
MSFlexGrid1.Width = Me.ScaleWidth
MSFlexGrid1.Height = Me.ScaleHeight
End Sub

1 comments:

Anonymous said...

cood

Post a Comment