C Program to Print All Permutations of a Given String

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.

  1. /*
  2.  * C program to find all permutations of letters of a string
  3.  */
  4. #include <stdio.h>
  5. #include <string.h> 
  6.  
  7. /* Function to swap values at two pointers */
  8. void swap (char *x, char *y)
  9. {
  10.     char temp;
  11.     temp = *x;
  12.     *x = *y;
  13.     *y = temp;
  14. }
  15. /*  End of swap()  */
  16.  
  17. /*  Function to print permutations of string  */
  18. void permute(char *a, int i, int n)
  19. {
  20.     int j;
  21.     if (i == n)
  22.         printf("%s\n", a);
  23.     else {
  24.         for (j = i; j <= n; j++)
  25.         {
  26.             swap((a + i), (a + j));
  27.             permute(a, i + 1, n);
  28.             swap((a + i), (a + j)); //backtrack
  29.         }
  30.     }
  31. }
  32.  
  33. /*  The main() begins  */
  34. int main()
  35. {
  36.     char a[20];
  37.     int n;
  38.     printf("Enter a string: ");
  39.     scanf("%s", a);
  40.     n = strlen(a);
  41.     printf("Permutaions:\n"); 
  42.     permute(a, 0, n - 1);
  43.     getchar();
  44.     return 0;
  45. }

$ 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.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.