Q:

C program to print all possible subsets of a given length in string

0

C program to print all possible subsets of a given length in string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now