ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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 Solution:

Read a string from the user and find all possible subsets of a given length in the string using C program.

Program:

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.