0% found this document useful (0 votes)
2 views2 pages

Subset Sum Program

The document provides a C program that finds all subsets of a given set of integers that sum up to a specified value. It prompts the user for the number of elements, the elements themselves, and the required sum, then outputs the subsets that meet the criteria. If no such subsets exist, it informs the user accordingly.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Subset Sum Program

The document provides a C program that finds all subsets of a given set of integers that sum up to a specified value. It prompts the user for the number of elements, the elements themselves, and the required sum, then outputs the subsets that meet the criteria. If no such subsets exist, it informs the user accordingly.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Subset Sum Program in C

C Program Code:
#include <stdio.h>
int main()
{
int n, d, i, j, found = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
int s[n];
printf("Enter elements:\n");
for(i = 0; i < n; i++)
{
scanf("%d", &s[i]);
}
printf("Enter required sum: ");
scanf("%d", &d);
printf("Subsets with sum %d are:\n", d);
for(i = 0; i < (1 << n); i++)
{
int sum = 0;
for(j = 0; j < n; j++)
{
if(i & (1 << j))
{
sum += s[j];
}
}
if(sum == d)
{
found = 1;
printf("{ ");
for(j = 0; j < n; j++)
{
if(i & (1 << j))
{
printf("%d ", s[j]);
}
}

printf("}\n");
}
}
if(found == 0)
{
printf("No subset found.\n");
}
return 0;
}

Sample Output
Enter number of elements: 4
Enter elements:
1 2 3 4
Enter required sum: 5
Subsets with sum 5 are:
{ 2 3 }
{ 1 4 }

You might also like