Seungjun
Seungjun

Reputation: 984

Program printing all SubSequences of array in C, prints same SubSequence two times

I'm trying to print out all possible SubSequences of the given array.

my current code works to a certain point, but have some error. In case of given array is {1,2,3}

the expected output is

0 0 0 
3 0 0 
2 0 0 
2 3 0 
1 0 0 
1 3 0 
1 2 0 
1 2 3 

but my output is

0 0 0 
3 0 0 
2 0 0 
2 3 0 
1 3 0 
1 3 0 
1 2 0 
1 2 3 

The problem is my code prints 1 3 0 two times not printing 1 0 0. Can anyone help me what caused this error in my code, please?

Here is my current code

#include <stdio.h>

void printAllSubSequences(int arr[], int index1, int  arr2[], int index2){
    
    if (index1 >= 3) {

        for(int i = 0; i < 3 ; i++){
            printf("%d ", arr2[i]);
        }
        printf("\n");
        return;
     }
     
    printAllSubSequences(arr, index1+1, arr2, index2);
    arr2[index2] = arr[index1];
    printAllSubSequences(arr, index1+1, arr2, index2+1);
}

int main(){
    int arr[3] = {1, 2, 3};
    int arr2[3];
    printAllSubSequences(arr, 0, arr2, 0);
    printf("\n");
}

Upvotes: 0

Views: 1247

Answers (1)

risingStark
risingStark

Reputation: 1155

The problem in your code is that after you initialized arr2[index2] = arr[index1]; you did not initialize it back to 0. Since the arrays in C or C++ are pass by reference, any change in any of the indices in any of recursive function call will reflect in successive function calls.

Hence, once you use arr2[index2] = arr[index1];, you also need to do arr2[index2] = 0; after the function call. Another thing, you need to initialize arr2 with 0 while declaring. It might work on your compiler but not in general. It is always a good practice to initialize it to 0.

Here's the corrected code.

#include <stdio.h>

void printAllSubSequences(int arr[], int index1, int  arr2[], int index2){
    
    if (index1 >= 3) {

        for(int i = 0; i < 3 ; i++){
            printf("%d ", arr2[i]);
        }
        printf("\n");
        return;
     }
     
    printAllSubSequences(arr, index1+1, arr2, index2);
    arr2[index2] = arr[index1];
    printAllSubSequences(arr, index1+1, arr2, index2+1);
    arr2[index2] = 0;
}

int main(){
    int arr[3] = {1, 2, 3};
    int arr2[3] = {0};
    printAllSubSequences(arr, 0, arr2, 0);
    printf("\n");
}

Upvotes: 2

Related Questions