Satyendra Singh
Satyendra Singh

Reputation: 67

Printing all possible combinations of elements in an array

During recursion, once elements are changed in an array, this change persist. How to pass array so that changes are done according to the call stack ? Once element at index 2 is set, its set in every function call.

Here's the code:

#include<stdio.h>

void recur(int flag[], int n, int idx){
    if(idx==n){
        for(int i=0; i<n; i++)
            if(flag[i])
                printf("%d  ", i);
        printf("\n");
        return;
    }

    recur(flag, n, idx+1);
    flag[idx] = 1;
    recur(flag, n, idx+1);
}
int main(){
    int flag[] = {0, 0, 0};
    recur(flag, 3, 0);
    return 0;
}

It gives me the following output:

2
1 2
1 2
0 1 2
0 1 2
0 1 2
0 1 2

Upvotes: 1

Views: 446

Answers (1)

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

If you want to keep the array intact, you need to revert any changes to the array you've made in your function. In this case you should store in a temporary variable the value of flag[idx] before changing it and then restore it:

#include <stdio.h>

void recur(int flag[], int n, int idx) {
  if (idx == n) {
    for (int i = 0; i < n; i++) {
      if (flag[i]) {
        printf("%d  ", i);
      }
    }
    printf("\n");
    return;
  }

  recur(flag, n, idx + 1);
  int temp = flag[idx];  // Change line 1
  flag[idx] = 1;
  recur(flag, n, idx + 1);
  flag[idx] = temp;  // Change line 2
}

int main() {
  int flag[] = {0, 0, 0};
  recur(flag, 3, 0);
  return 0;
}

See it in ideone: https://ideone.com/Q6Vb7A

Upvotes: 3

Related Questions