REM    Magic.bas - Makes a magic square using Loubere's rule
REM  The Magic Square is of Odd order and the Maximum size can be 19.
DIM MAGIC(19, 19)
CORRECT = 0
DO WHILE NOT CORRECT
  INPUT "Enter size/order of Magic Square(Odd < 20)", NDIM
  IF NDIM > 0 AND NDIM = INT(NDIM) AND (NDIM MOD 2 = 1) AND NDIM < 20 THEN CORRECT = 1: EXIT DO
  PRINT "Invalid Data. Re-enter"
LOOP
ROWNUM = 1: COLNUM = NDIM \ 2 + 1
MAGIC(ROWNUM, COLNUM) = 1
FOR I = 2 TO NDIM * NDIM
   'IF AT RIGHT HAND CORNER
   IF ROWNUM = 1 AND COLNUM = NDIM THEN NEWROW = 2: NEWCOL = COLNUM: GOTO 100
   ' MOVE UP 1 ROW & TO THE RIGHT
   NEWROW = ROWNUM - 1: NEWCOL = COLNUM + 1
   IF NEWROW < 1 THEN NEWROW = NEWROW + NDIM
   'ABOVE LINE MEANS GONE OFF THE TOP
   IF NEWCOL > NDIM THEN NEWCOL = NEWCOL - NDIM
   'ABOVE LINE MEANS GONE OFF THE RIGHT
   'NOW, FIND EMPTY SLOT BY GOING DOWN ROW BY ROW
100 DO UNTIL MAGIC(NEWROW, NEWCOL) = 0
     NEWROW = ROWNUM + 1
     NEWCOL = COLNUM
   LOOP
   ROWNUM = NEWROW
   COLNUM = NEWCOL
   MAGIC(ROWNUM, COLNUM) = I
NEXT

' PRINT THE MAGIC SQUARE GENERATED
FOR I = 1 TO NDIM
  FOR J = 1 TO NDIM
    PRINT USING "### "; MAGIC(I, J);
  NEXT
  PRINT
NEXT

END

