This is a C program to permute all the letters of an input string.
This algorithm finds all permutations of the letters of a given string. It is a recursive algorithm using concept of backtracking.
Here is the source code of the C program to permute all letters of an input string. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to find all permutations of letters of a string
*/
#include <stdio.h>
#include <string.h>
/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
/* End of swap() */
/* Function to print permutations of string */
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else {
for (j = i; j <= n; j++)
{
swap((a + i), (a + j));
permute(a, i + 1, n);
swap((a + i), (a + j)); //backtrack
}
}
}
/* The main() begins */
int main()
{
char a[20];
int n;
printf("Enter a string: ");
scanf("%s", a);
n = strlen(a);
printf("Permutaions:\n");
permute(a, 0, n - 1);
getchar();
return 0;
}
$ gcc permute.c -o permute $ ./permute Enter a string: SAN All possible permutations are: SAN SNA ASN ANS NAS NSA
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Next Steps:
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice Computer Science MCQs
- Watch Advanced C Programming Videos
- Buy Computer Science Books
- Buy C Books
- Practice BCA MCQs