Integer subset generator source code

This snippet submitted by treenef on 2005-12-14. It has been viewed 3702 times.
Rating of 5.3 with 10 votes

/*========================================
  
  Given: An integer 'N'
  Output: To print out all possible subsets
          in lexicographic order
  Notes: Excludes the trivial empty subset
         {}
          
 ========================================*/
#include <iostream>

using namespace std;

int main()
{
    int i, k=1, n; 
    int x[100];

    cout<<"Enter N >>";
    cin>>n;

    

    x[1] = 1;

    while (k)
    {
        for (i=1; i <= k; i++) 
        cout<<" "<<x[i];
        cout<<"\n";
        

        if (x[k] == n)
        {
            k--;
            x[k]++;
        }
        else
        {
            k++;
            x[k] = x[k-1] + 1;
        }
     }
     return 0;
}




More C and C++ source code snippets

Add a snippet!