## C Program To Find Permutations of String using Recursion

Learn How To Find Permutations of String in C Programming. This C Program To Permute all letters of a string without Recursion makes use of Pointers. The C program prints all permutations of the string without duplicates. You can also modify the code to print permutations of a string with duplicates.

#### What is Permutation of a String?

String Permutations is a way to uniquely arrange all the letters of the string. These permutations may or may not include repetitions which can be modified in your program code.

Recursion is the best possible way of finding permutations of the string as it helps to build a clean code and also eases the debugging.

#### Example

**String:** xyz

**Permutations:**

xyz

xzy

yxz

yzx

zxy

zyx

#### Formula To Find Permutations of a given String

#### Algorithm To Calculate Permutations of a String

1 2 3 4 5 6 | If the String is Empty Return the only possible Permutation which is an Empty List Else For each Element of the String Put the Element at the first place Recursively find all the Permutations of the rest of the List |

#### C Program For Permutations of String using Recursion

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include<stdio.h> #include<string.h> void string_permutation(char *str, int j, int length) { int i; if(j == length) { printf("%s\n", str); } else { for(i = j; i <= length; i++) { swapping((str + j), (str + i)); string_permutation(str, j + 1, length); swapping((str + j), (str + i)); } } } void swapping(char *a, char *b) { char temp; temp = *a; *a = *b; *b = temp; } int main() { char str[20]; int length; printf("\nEnter a String:\t"); scanf("%s", str); length = strlen(str); printf("Permutations of String %s:\n", str); string_permutation(str, 0, length - 1); getchar(); return 0; } |

#### Output

In case you get any compilation errors or any doubts in this C Program To Find Permutation of a String without Iterative method, let us know about it in the Comment Section below.

Thanks for this one! I was looking for a code that prints distinct permutations of any given string. This one does exactly that.

The swapping functions uses call by reference, if I am not mistaken.

Nice String Permutation Algorithm. Well, I have checked other codes on your website, it is a gold for us beginner programmers. Thanks a lot.

It is so simple to implement once you understand the logic.