11,631,992 members (63,526 online)
Tip/Trick

Magic square in VB.NET

, 14 Dec 2011 CPOL 10.3K 3
 Rate this:
Calculating the magic square in VB.NET.

This is a simple console application developed with VB.NET for gerating the magic square of an odd number.

The magic squares problem leads to work into areas of mathematics such as theories of groups, lattices, Latin squares, determinants, partitions, matrices, and congruence arithmetic. Computer scientists are also perplexed by the difficulty of generating all magic squares of larger sizes.

In the solution, `Sum` shows the summation of any row, column, or diagonal.

The complete code is like this....

```Module Module1
Public s, size As Integer

Sub Main()
Dim n As Integer = 1
Dim i As Integer = 1
Dim j As Integer = 2

Console.WriteLine()
Console.Write("ENTER THE SIZE OF MAGIC SQUARE:  ")
size = s
Dim sum As Integer = 0

Dim ans(s, s) As Integer

If s <> 3 Then
Dim tmp As Integer = (s - 3) \ 2
i = i + tmp
j = j + tmp
End If

While n <= s * s

If ans(i, j) = 0 Then
ans(i, j) = n
Else
n = n - 1
i = i + 2
End If

i = i - 1
j = j + 1

If (i = -1 And j = s) Then
i = 0
j = 1
End If

If j >= s Then
j = j - s
End If

If i < 0 Then
i = s - 1
End If
n = n + 1
End While

Console.WriteLine()
Console.WriteLine("MAGIC SQUARE:")
Console.WriteLine()

For k As Integer = 0 To size - 1
For l As Integer = 0 To size - 1
Console.Write("    " & ans(k, l))
Next
Console.WriteLine()
Next

Console.WriteLine()
sum = ans(s \ 2, s \ 2) * s
Console.Write("SUM: " & sum)

End Sub

End Module```

The summation is based on this equation:

`SUM =  { N ( N^2 + 1 ) } /  2`

Where the N is number of row or column. If N = 5, then the result will be 65.

Share

 Software Developer India
No Biography provided

You may also be interested in...

 First Prev Next
 Re: Okay so what does it mean Peter Hawke22-Dec-11 12:55 Peter Hawke 22-Dec-11 12:55
 Okay so what does it mean
 Re: :) NikulDarji20-Dec-11 2:40 NikulDarji 20-Dec-11 2:40
 Re: I agree, that paying attention to the logic behind the progr... Member 841302020-Dec-11 1:44 Member 8413020 20-Dec-11 1:44
 Dim ans(s, s) As Integer What does the ans(s, s) mean. Is ... Peter Hawke20-Dec-11 12:49 Peter Hawke 20-Dec-11 12:49
 Re: Yes....:) NikulDarji20-Dec-11 18:30 NikulDarji 20-Dec-11 18:30
 Reason for my vote of 2 I'll add to the previous dissatisfac... Member 841302019-Dec-11 23:17 Member 8413020 19-Dec-11 23:17
 Re: Don't u think u have to pay attention on logic behind this p... NikulDarji20-Dec-11 1:24 NikulDarji 20-Dec-11 1:24
 Reason for my vote of 1 How about explaining what a 'magic s... pt140118-Dec-11 6:02 pt1401 18-Dec-11 6:02
 Last Visit: 31-Dec-99 18:00     Last Update: 28-Jul-15 8:42 Refresh 1