Wednesday 22 November 2017

C++ Program to Permute All Letters of an Input String


Code:

#include       iostream
#include       string.h

using namespace std;

// A function to swap character values of the string using references.
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}

// A function to print permutation using recursion technique.
void Permute(char *a, int i, int n) 
{
int j; 

if (i == n-1)
cout<<"\n"<
else
{
for (j = i; j < n; j++)
{
// Swap the character at ith index with every other value to get all the possible permutations.
swap(a[i], a[j]);
Permute(a, i + 1, n);
swap(a[i], a[j]);
}
}
}

int main()
{
char str[21];
int len, count = 1;

cout<<"\nEnter a string: ";
cin>>str;
len = strlen(str);

for (i = 0; i < N; i++)
{
count *= (i+1);
}

// Print the permutation's count.
cout<<"\nThe number of permutations possible is: "<

// Call permute() function to print all the permutation.
Permute(str, 0, len);

return 0;
}


Output:

Case 1:
Enter a string: abc

The number of permutations possible is: 6

        abc
        acb
        bac
        bca
        cba
        cab

Case 2:
Enter a string: abcd

The number of permutations possible is: 24

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




More C++ Programs:















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...