Hi, I was trying to write a C program that lists all of the subsets of the set {1,2,...,n}. The program should be ask number of elements in the set from the keyboard, and the order must be shown in the example.
For example;
Enter the number of elements: 3
The subsets of {1,2,3} are :
1.<Empty set>
2. {1}
3. {2}
4. {3}
5. {1,2}
6. {1,3}
7. {2,3}
8. {1,2,3}
Here is my codes, I have trouble, when I entered 5,4, or 3. (Basiccally entered>=3) It doesnt show all subsets, I spend too much time for this code and I dont wanna get bad grade. Can anybody help me to fix this code, Where şs the problem, and how to fix it?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <stdio.h>
int main()
{
int sayi, subset, i, j, start, index, a[50], x;
printf("Enter the number of elements :");
scanf("%d", &sayi);
for(x = 0; x < sayi; x++)
{
a[x] = x + 1;
}
printf("The subsets are :\n");
for(subset = 1; subset <= sayi; subset++)
{
for(start = 0; start <= sayi - subset; start++)
{
if(subset == 1)
{
printf("{%d}\n", a[start]);
}
else
{
index = start + subset - 1;
for(j = index; j < sayi; j++)
{
for(i = start; i < index; i++)
{
printf("{%d}", a[i]);
}
printf("{%d}\n", a[j]);
}
}
}
}
printf("{ }");
/* main() is supposed to return a value */
return 0;
}
| |