Don’t worry, unlock all articles / blogs on PrepInsta by just simply logging in on our website
Given a list arr of N integers, print sums of all subsets in it in C
October 13, 2022
Sums of all Subsets in C
Here, in this page we will discuss the program for printing the sums of all subsets in C programming language. We are given with a list array of N integers, and need to print the all subsets sums.
Method Discussed :
Method 1 : Iterative Method
Method 2 : Recursive Method
Method 1 :
The total number of subset will be 2n, where n is the size of the array.
Run a loop from 0 to 2n -1.
Now, Pick all array elements which correspond to 1s in binary representation of ith number.
#include <stdio.h>
void subsetSums(int arr[], int n)
{
// There are total 2^n subsets
long long total = 1 << n;
// Consider all numbers from 0 to 2^n - 1
for (long long i = 0; i < total; i++) {
long long sum = 0;
for (int j = 0; j < n; j++)
if (i & (1 << j))
sum += arr[j];
// Print sum of picked elements.
printf("%lld ", sum);
}
}
int main()
{
int arr[] = { 4, 3, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
subsetSums(arr, n);
return 0;
}
In this method we will discuss the recursive way to find the subsets sum, in this either we will take the elements value in the sum or not. Based on this approach we will find the subsets sum.
Login/Signup to comment