Print all permutations of a string in c

C program for Print all permutations of a string. Here problem description and explanation.

// C program for
// Print all permutations of a string
#include <stdio.h>

// Swap two elements in given string
// i and j is location
void swap(char str[], int i, int j) {
	char temp = str[i];
	str[i] = str[j];
	str[j] = temp;
}
// Method which is print all permutations of given string
void permutation(char str[], int n, int size) {
	if (n > size) {
		return;
	}
	if (n == size) {
		printf("%s\n", str);
		return;
	}
	for (int i = n; i < size; ++i) {
		// swap the array element
		swap(str, i, n);
		permutation(str, n + 1, size);
		// swap the array element
		swap(str, i, n);
	}
}
int main() {
	// Given string is form of array
	char str1[] = "ABC";
	// Get the size 
	int size = sizeof(str1) / sizeof(str1[0]);
	permutation(str1, 0, size - 1);
	printf("\n");
	char str2[] = "abcd";
	// Get the size 
	size = sizeof(str2) / sizeof(str2[0]);
	permutation(str2, 0, size - 1);
	return 0;
}

Output

ABC
ACB
BAC
BCA
CBA
CAB

abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved