Here are C++ programs to print all subsets or all combinations of elements in a set. First program print all subset of a set using for-loop, second program uses bitwise operator to print all subsets and program uses recursion.
Method 1 : C++ programs to print all subsets or all combinations of elements in a set using for-loop
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int a[20],n,tsets,d,rem;
cout<<"Enter how many elements in set ";
cin>>n;
cout<<"Enter elements ";
for(int i=0;i<n;i++)
cin>>a[i];
tsets=pow(2,n);
for(int i=0;i<tsets;i++)
{
cout<<endl<<"(";
d=i;
for(int j=0;d>0;j++)
{
rem=d%2;
d/=2;
if(rem>0)
cout<<" "<<a[j]<<" ";
}
cout<<")";
}
return 0;
}
#include<math.h>
using namespace std;
int main()
{
int a[20],n,tsets,d,rem;
cout<<"Enter how many elements in set ";
cin>>n;
cout<<"Enter elements ";
for(int i=0;i<n;i++)
cin>>a[i];
tsets=pow(2,n);
for(int i=0;i<tsets;i++)
{
cout<<endl<<"(";
d=i;
for(int j=0;d>0;j++)
{
rem=d%2;
d/=2;
if(rem>0)
cout<<" "<<a[j]<<" ";
}
cout<<")";
}
return 0;
}
Method 2 : C++ programs to print all subsets or all combinations of elements in a set using bitwise operator
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int a[20],n,tsets;
cout<<"Enter how many elements in set ";
cin>>n;
cout<<"Enter elements ";
for(int i=0;i<n;i++)
cin>>a[i];
tsets=pow(2,n);
for(int i=0;i<tsets;i++)
{
cout<<endl<<"(";
for(int j=0;j<n;j++)
{
if(i&(1<<j))
cout<<" "<<a[j]<<" ";
}
cout<<")";
}
return 0;
}
#include<math.h>
using namespace std;
int main()
{
int a[20],n,tsets;
cout<<"Enter how many elements in set ";
cin>>n;
cout<<"Enter elements ";
for(int i=0;i<n;i++)
cin>>a[i];
tsets=pow(2,n);
for(int i=0;i<tsets;i++)
{
cout<<endl<<"(";
for(int j=0;j<n;j++)
{
if(i&(1<<j))
cout<<" "<<a[j]<<" ";
}
cout<<")";
}
return 0;
}
Method 3 : C++ programs to print all subsets or all combinations of elements in a set using recursion
#include<iostream>
#include<math.h>
using namespace std;
void print(int (&a)[10],int i,int j)
{
if(j<0)
return;
if(i&(1<<j))
cout<<a[j]<<" ";
print(a,i,j-1);
}
void set(int (&a)[10],int i,int n)
{
if(i==0)
return ;
print(a,i,n);
cout<<endl;
set(a,i-1,n);
}
int main()
{
int n,result,a[10];
cout<<"How many numbers to be entered : ";
cin>>n;
cout<<"Enter numbers ";
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"Subsets : "<<endl;
set(a,pow(2,n)-1,n);
return 0;
}
#include<math.h>
using namespace std;
void print(int (&a)[10],int i,int j)
{
if(j<0)
return;
if(i&(1<<j))
cout<<a[j]<<" ";
print(a,i,j-1);
}
void set(int (&a)[10],int i,int n)
{
if(i==0)
return ;
print(a,i,n);
cout<<endl;
set(a,i-1,n);
}
int main()
{
int n,result,a[10];
cout<<"How many numbers to be entered : ";
cin>>n;
cout<<"Enter numbers ";
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"Subsets : "<<endl;
set(a,pow(2,n)-1,n);
return 0;
}
No comments:
Post a Comment