crecursionmagic-square

Magic square in a recursive form in C


I am working on a magic square problem, the size of the square will be an odd number between 3 to 99. Here is the result of a 5x5 square:

   15    8    1   24   17

   16   14    7    5   23

   22   20   13    6    4

    3   21   19   12   10

    9    2   25   18   11

The program works fine with a for loop, but I've been asked to rewrite this using recursion.

Can anyone give me some direction? Much appreciated!

    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            square[i][j] = 0;
        }
    }

    square[i][j] = k;    // Start from the middle of the first row (1)

    for (k = 2; k <= size * size; k++) {
        // Move up and left    

        if (square[I][j]) {
            // Move down if space is occupied
        } 

        square[I][j] = k;
    }

I tried to rewrite it in recursive, but got "Segmentation fault: 11".

void magic(int square[][size], int size, int k, int i, int j) {

    if (k >= size * size) {
        return;
    } else {
        // Move up and left   
        
        if (square[I][j]) {
            // Move down if space is occupied
        } 

        square[I][j] = k;

        magic(square, size, k + 1, i, j);
    }
}

Solution

  • Turns out the recursion I wrote is correct all along, the compile error come from the 2D array parameter of the recursive function, the size of that 2D array is dynamic assign from the user after the program compiled, in the old version I defined the function with the maximum value that's why the function only works when the size is maximum.