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?