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?
In the first case:
jis a global variable so when executeelse Try(k + 1);j is reinitialized with zero and after and exitTry(k + 1);the value ofjnow equal 2, so it will exist the for loop and end your code.But in the second case:
jis a local variable so when enteringtryfunction again, it seesjas a different variable than the oldj. It's not the same variable you try to access.Be careful when you write a recursive function. Avoid global variables.