~cpp public class MagicSquare { int _size; int _x, _y; int _board[][]; public MagicSquare(int size) { _size = size; _board = new int[_size][_size]; for(int i = 0 ; i < _size ; ++i) for(int j = 0 ; j < _size ; ++j) _board[i][j] = 0; _x = _size/2; _y = 0; } void calcNextCoord() { int oldX = _x; int oldY = _y; _x = setValidCoord(++_x); _y = setValidCoord(--_y); if(_board[_y][_x] != 0) { _x = oldX; _y = oldY; ++_y; } } int setValidCoord(int c) { if(c == -1) c = _size - 1; else if(c == _size) c = 0; return c; } void traverseSquare() { for(int i = 1 ; i <= _size*_size ; ++i) { _board[_y][_x] = i; calcNextCoord(); } } void showBoard() { for(int i = 0 ; i < _size ; ++i) { for(int j = 0 ; j < _size ; ++j) System.out.print( _board[i][j] + " "); System.out.println(" "); } } public static void main(String args[]) { MagicSquare ms = new MagicSquare(5); ms.traverseSquare(); ms.showBoard(); } }