-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?

2
  • 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. Commented Oct 28, 2021 at 23:20
  • What is backtracked here? Can you explain the algorithm a bit more? Commented Oct 29, 2021 at 9:52

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.