C Exercises: Generate permutations of a given string
8. Permutations of a String Using Pointers
Write a program in C to print all permutations of a given string using pointers.
Sample Solution:
C Code:
#include <stdio.h>
#include <string.h>
// Function to swap characters
void changePosition(char *ch1, char *ch2)
{
char tmp;
tmp = *ch1;
*ch1 = *ch2;
*ch2 = tmp;
}
// Function to generate permutations of a string
void charPermu(char *cht, int stno, int endno)
{
int i;
if (stno == endno)
printf("%s ", cht); // Print the generated permutation when stno equals endno
else
{
for (i = stno; i <= endno; i++)
{
changePosition((cht + stno), (cht + i)); // Swap characters at positions stno and i
charPermu(cht, stno + 1, endno); // Recursively generate permutations for the rest of the string
changePosition((cht + stno), (cht + i)); // Restore the original string by swapping back
}
}
}
// Main function
int main()
{
char str[] = "abcd"; // The input string
printf("\n\n Pointer : Generate permutations of a given string :\n");
printf("--------------------------------------------------------\n");
int n = strlen(str); // Get the length of the string
printf(" The permutations of the string are : \n");
charPermu(str, 0, n - 1); // Call function to generate permutations
printf("\n\n");
return 0;
}
Sample Output:
Pointer : Generate permutations of a given string : -------------------------------------------------------- The permutations of the string are : abcd abdc acbd acdb adcb adbc bacd badc bcad bcda bdca bdac cbad cbda cabd cadb cdab cdba db ca dbac dcba dcab dacb dabc
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C program to generate all permutations of a given string recursively using pointers to swap characters.
- Write a C program to print all distinct permutations of a string with duplicate characters using pointer manipulation.
- Write a C program to generate and display permutations of a string in lexicographical order using pointers.
- Write a C program to recursively generate permutations of a string and then reverse each permutation using pointer arithmetic.
C Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a program in C to store n elements in an array and print the elements using pointer.
Next: Write a program in C to find the largest element using Dynamic Memory Allocation.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics