Magic square in a recursive form in C

493 views Asked by At

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);
    }
}
2

There are 2 answers

0
Bryce Chan On BEST ANSWER

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.

0
John Bollinger On

Since building a magic square is naturally iterative, and not at all naturally recursive, I can only suppose that the instructor's objective is to emphasize the fact that any iterative algorithm can be rewritten as a recursive one. (The reverse is also true.) So how does that work?

An iterative algorithm has this abstract form:

iterative(initial_index, final_index):    
    i := initial_index
    current_state := initial_state
    loop_top:
    if i > final_index then
        return current_state
    update_state(current_state, i)
    i := i + 1
    go to loop_top

That can be rewritten recursively like so (for example):

recursive(initial_index, final_index):
    if initial_index > final_index then
        return initial_state                   // the same initial_state as before
    current_state = recursive(initial_index, final_index - 1)  // recursion
    update_state(current_state, final_index)   // the same update_state() as before
    return current_state

Details of how to map your particular algorithm onto that or something equivalent are left as the exercise they are meant to be.