Home »
C programs »
C string programs
C program to print all possible subsets of a given length in string
Here, we are going to learn how to print all possible subsets of a given length in string in C programming language?
Submitted by Nidhi, on July 20, 2021
Problem statement
Read a string from the user and find all possible subsets of a given length in the string using C program.
C program to print all possible subsets of a given length in string
The source code to print all possible subsets of a given length in the string is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to print all possible subsets
// of a given length in string
#include <stdio.h>
#include <string.h>
int main()
{
char str[32];
int i = 0;
int j = 0;
int l1 = 0;
int l2 = 0;
int ind = 0;
int start = 0;
printf("Enter string: ");
scanf("%s", str);
l1 = strlen(str);
printf("Enter length: ");
scanf("%d", &l2);
printf("The possible subsets are:\n");
for (i = 1; i <= l1; i++) {
if (ind - start + 1 == i) {
if (i == l2) {
for (j = ind; j < l1; j++) {
for (i = start; i < ind; i++)
printf("%c", str[i]);
printf("%c\n", str[j]);
}
if (start != i) {
start++;
ind = start;
}
}
else
ind++;
}
}
return 0;
}
Output
RUN 1:
Enter string: IncludeHelp
Enter length: 3
The possible subsets are:
Inc
Inl
Inu
Ind
Ine
InH
Ine
Inl
Inp
RUN 2:
Enter string: Hello
Enter length: 2
The possible subsets are:
He
Hl
Hl
Ho
Explanation
In the main() function, we read a string and length from the user and find all possible subsets of input length and printed the result on the console screen.
C String Programs »