Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Printing all subsets of {1,2,3,...n} without using array or loop in C program
Given a positive integer n, we have to print all the subsets of the set {1, 2, 3, 4,… n} without using any array or loops. For example, if n = 3, we need to print all subsets of {1, 2, 3} which are {1 2 3}, {1 2}, {2 3}, {1 3}, {1}, {2}, {3}, and { }.
Since we cannot use loops or arrays, recursion is the only way to solve this problem. We use binary representation to generate subsets efficiently.
Syntax
void generateSubsets(int n, int currentNum); void printSubset(int bitPosition, int num, int totalBits);
Algorithm Approach
The approach uses binary representation where each bit corresponds to an element in the set −
- Start from num = 2^n - 1 down to 0
- Each bit in the binary representation of num represents whether to include that element
- If the i-th bit is set, include the i-th element in the subset
- Recursively process all possible combinations
Working Example
For n = 3, we start from num = 2^3 - 1 = 7 −
| Number | Binary (3 bits) | Subset |
|---|---|---|
| 7 | 1 1 1 | {1 2 3} |
| 6 | 1 1 0 | {1 2} |
| 5 | 1 0 1 | {1 3} |
| 4 | 1 0 0 | {1} |
| 3 | 0 1 1 | {2 3} |
| 2 | 0 1 0 | {2} |
| 1 | 0 0 1 | {3} |
| 0 | 0 0 0 | { } |
Example
#include <stdio.h>
#include <math.h>
/* This function recursively prints the subset corresponding
to the binary representation of num */
int subset(int bitn, int num, int num_of_bits) {
if (bitn >= 0) {
/* Print number in subset only if the corresponding bit is set */
if ((num & (1 << bitn)) != 0) {
printf("%d ", num_of_bits - bitn);
}
/* Check the next bit */
subset(bitn - 1, num, num_of_bits);
} else {
return 0;
}
return 1;
}
/* Function to print all subsets */
int printSubSets(int num_of_bits, int num) {
if (num >= 0) {
printf("{ ");
/* Print the subset corresponding to binary representation of num */
subset(num_of_bits - 1, num, num_of_bits);
printf("}");
/* Recursively call function to print next subset */
printSubSets(num_of_bits, num - 1);
} else {
return 0;
}
return 1;
}
int main() {
int n = 3;
printf("All subsets of {1, 2, ..., %d}:<br>", n);
printSubSets(n, (int)(pow(2, n)) - 1);
printf("<br>");
return 0;
}
All subsets of {1, 2, ..., 3}:
{ 1 2 3 }{ 1 2 }{ 1 3 }{ 1 }{ 2 3 }{ 2 }{ 3 }{ }
Key Points
- The algorithm generates 2^n subsets for a set of n elements
- Time complexity is O(2^n * n) due to recursive calls and bit checking
- Space complexity is O(n) for recursion stack depth
- No arrays or loops are used, only recursive functions
Conclusion
Using binary representation with recursion effectively generates all subsets without arrays or loops. Each bit position determines element inclusion, making this approach both elegant and efficient for the given constraints.
