GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

all subarray of array - iterative

Print all the sub arrays of array with iterative approach.subarray elements can non contiguous It does not matter complexity. It can be O(n^3) but want iterative approach.

Array - [1, 2, 3, 4]

[1] [2] [3] [4] [1 2] [1 3 ] [1 4] [2 3] [2 4] [3 4] [1 2 3] [1 3 4] [2 3 4] ...

 

asked Feb 26 by anonymous

1 Answer

void findIterativeSubset()
{
    int i, j;
    int arr[] = { 1, 2, 3, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    bool flag = false;
    for (i = 0; i < (1 << (n)); i++)   // 1 << n : The number of subsets
    {
        for (j = 0; j < n; j++)      // Compare bits to the number of elements
        {
            if (i & (1 << j))      // Output jth element when jth bit of i is 1
                cout << "[" << arr[j] << "]" << " ";
        }
        if (j == n && !flag)
        {
            cout << "[" << "]" << " ";
            flag = true;
        }
        cout << endl;
    }
}

 

 

answered Feb 28 by Nitish Nandwana
edited Feb 28 by Nitish Nandwana
...