write a c program to print all possible combinations of given characters. For example if given characters are [a b c d] then ,its all possible combinations are as follows

combination of characters [a b c d]

a
b
c
d
a b
a c
a d
b c
b d
c d
a b c
a b d
a c d
b c d
a b c d

 

print all possible combinations of given characters

c program to print all possible combinations of given characters

#include<stdio.h>

void comb(char *str, char *out, int start, int next, int r, int strlen);

int main() {

	char string[] = "abcd";
	// helper string for output
	int sizeof_string = sizeof(string) - 1;
	char out[sizeof_string];

	// call comb
	for (int r = 1; r <= sizeof_string; r++)
		comb(string, out, 0, 0, r, sizeof_string);

	return 0;
}

void comb(char *str, char *out, int start, int next, int r, int strlen) {
	int i = 0;
	if (next == r) {
		for (i = 0; i < r; i++) {
			printf("%c ", out[i]);
		}
		printf("\n");
		return;
	}

	if (start == strlen)
		return;

	out[next] = str[start];
        // select next
	comb(str, out, start + 1, next + 1, r, strlen);
        // do not select next
	comb(str, out, start + 1, next, r, strlen);
}

How it works

Let us see our input [ a b c d]. A combination is a selection problem. If we need to find all possible combinations of r element ( Ex. r =2) ,then in this case, to make a combination of two either we select a character from input [a b c d] or we do not select. Our program has the same logic as it is getting called with following

        
        // select next
	comb(str, out, start + 1, next + 1, r, strlen);
        // do not select next
	comb(str, out, start + 1, next, r, strlen);

With the help of a temporary array out, in case of character selection we put the selected character in helper array out.



Related Contents to follow