-2

I have tried a backtracking algorithm and receive different results when I initialize a variable inside and outside a for loop, but I don't understand why.

#include <stdio.h>

int a[10];
int n;
int i;
int j;   //difference

void display(){
    for (i = 1; i <= n; i++) printf("%d", a[i]);
    printf("%\n");
}

void Try(int k){
    for (j = 0; j <= 1; j++){                //difference
        a[k] = j;
        if (k == n) display();
        else Try(k + 1);
    } 
}

int main(){
    n = 2;
    Try(1);
}

and

#include <stdio.h>

int a[10];
int n;
int i;
//int j;   //difference

void display(){
    for (i = 1; i <= n; i++) printf("%d", a[i]);
    printf("%\n");
}

void Try(int k){
    for (int j = 0; j <= 1; j++){                //difference
        a[k] = j;
        if (k == n) display();
        else Try(k + 1);
    } 
}

int main(){
    n = 2;
    Try(1);
}

The result of the first code is just 00, 01 but the result of the second code is 00, 01, 10, 11 (the expected result).

Why does it have that difference?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 3
    In the first case all the recursive calls share the same value of `j`. Which means the value of `j` in the caller will no longer be the same after a recursive call. Using global variables all over the place like this is extremely bad practice. – kaylum Oct 28 '21 at 23:20
  • What is backtracked here? Can you explain the algorithm a bit more? – ngong Oct 29 '21 at 09:52

1 Answers1

1

In the first case: j is a global variable so when execute else Try(k + 1); j is reinitialized with zero and after and exit Try(k + 1); the value of j now equal 2, so it will exist the for loop and end your code.

But in the second case: j is a local variable so when entering try function again, it sees j as a different variable than the old j. It's not the same variable you try to access.

Be careful when you write a recursive function. Avoid global variables.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278