Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
int printSubset(char *set,int &elements)
{
	int total_subsets = pow(2,elements);
	cout<<"\n Total subset are = 2^"<< elements <<" = "<< total_subsets <<endl;
	cout<<"\nEmpty set";
    
    for(int c=0; c<total_subsets; c++)
    {
      for(int j=0; j<elements; j++)
       {
		if(c&(1<<j))
          {
          	 cout<< set[j];
          }          
	  }
	  cout<<"\n\n";
    }
}


What I have tried:

Actually this code is for making subsets of a set
But i dont understand the following code that how does it works


Especially the
if condition so please tell me about the condition.
for(int c=0; c<total_subsets; c++)
{
  for(int j=0; j<elements; j++)
   {
if(c&(1<<j))
      {
         cout<< set[j];
      }
   }
  cout<<"\n\n";
}
Posted
Updated 21-Jun-18 18:59pm

1 solution

When you don't understand a bit of code, look at it and dissect it into it's component parts.
C++
if(c&(1<<j))
Breaks down into
C++
if (...)
and
C++
c&(1<<j)
The first part I know you understand - it's a normal if, and the second part is the condition which evaluates to true or false.
C++
c & (1 << j)
;Is also in two parts:
C++
c & ...
And
C++
1 << j
The first part is a binary AND of the two values: c and the second part, and a binary AND is simple: for each bit in the inputs, the resulting bit is 1 if and only if both the input bits are 1. Otherwise it's a 0. (Interesting Facts about Bitwise Operators in C - GeeksforGeeks[<a href="https://www.geeksforgeeks.org/interesting-facts-bitwise-operators-c/" target="_blank" title="New Window>^] should help)
The second part is also simple: it's a 1 shifted j places to the right (the link above also explains this). So if j is 0 then it results in 1, for j == 1 it results in 2, for j = 2 it gives 4, and so on.

So the whole if is checking for a 1 bit in a specific position in c

This is all in the documentation: Operators in C / C++ - GeeksforGeeks[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900