Can any one tell me what the highlighted code does

#include <bits/stdc++.h>
using namespace std;

void allPossibleSubset(int arr[], int n)
{
int count = pow(2, n);
// The outer for loop will run 2^n times to print all subset .
// Here variable i will act as a binary counter
for (int i = 0; i < count; i++) {
// The inner for loop will run n times ,
// As the maximum number of elements a set can have is n
// This loop will generate a subset
for (int j = 0; j < n; j++) {
// This if condition will check if jth bit in
// binary representation of i is set or not
// if the value of (i & (1 << j)) is not 0 ,
// include arr[j] in the current subset
// otherwise exclude arr[j]
if ((i & (1 << j)) != 0)
** cout << arr[j] << " ";**
}
cout << ā€œ\nā€;
}
}

int main()
{
int n;

cout << "Enter size of the set\n";
cin >> n;

int arr[n];
cout << "Enter Elements of the set\n";
for (int i = 0; i < n; i++)
    cin >> arr[i];

allPossibleSubset(arr, n);

return 0;

}

1 Like

Click one first link of [google search results]((i & (1 << j) - Google Search)

.

1 Like

(i & (1 << j)) is checking if the jth bit in i is 0 or 1. You are doing left shift on 1 by j. If the jth bit of i is 1 then (i & (1 << j)) will be greater than or equal to one, otherwise zero.
You can also do (1 & (i >> j)) -> right shift i (j times) and then AND with 1, to get either 0 or 1 (instead of >= 1)

1 Like