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

«
»
This C++ Program Permutes All Letters Of An Input String.

It iterates from the 0th letter to last letter in a string, swaps values and recursively call permute function to print values.

The program has an input as a string. This prints permutation of all letters of an input string.

advertisement

Here is source code of the C++ Program to Find Permute All Letters of an Input String. The C++ program is successfully compiled and run on g++-4.3.2 on a Linux system. The program output is also shown below.

  1. //This is a C++ Program to Permute All Letters Of An Input String.
  2. #include <iostream>
  3. #include <string>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7. void permute (string temp_str, int start, int end)
  8. {
  9.   int i;
  10.   if (start == end){
  11.     cout << temp_str << " ";
  12.   }
  13.   else{
  14.     for (int i = start; i < temp_str.length (); ++i){
  15.       swap (temp_str[start], temp_str[i]);
  16.       permute (temp_str, start + 1, end);
  17.       swap (temp_str[start], temp_str[i]);
  18.     }
  19.   }
  20. }
  21. int main()
  22. {
  23.   string input_str;
  24.   bool flag = false;
  25.   cout << "Enter String : ";
  26.   cin >> input_str;
  27.   for (int i = 0; i < input_str.length () - 1; ++i)
  28.   {
  29.     if (input_str[i] == input_str[i + 1])
  30.     {
  31.     flag = true;
  32.     break;
  33.     }
  34.     else {
  35.       flag = false;
  36.       break;
  37.     }
  38.   }
  39.   if (flag)
  40.   {
  41.     cout << "The permutation of " << input_str << " is : " << input_str << endl;
  42.   }
  43.   else 
  44.   {
  45.     cout << "The permutations of " << input_str << " are : " << endl;
  46.     permute (input_str, 0, input_str.length () - 1);
  47.   }
  48.   cout << endl;
  49.   return 0;
  50. }

Output :

advertisement
 
$ g++ PermuteString.cpp
$ ./a.out
 
Enter String : bac
The permutations of bac are : bac bca abc acb cab cba 
Enter String : aaaa
The permutation of aaaaa is : aaaaa
 
Enter String : b
The permutations of b are : b

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
Here’s the list of Best Reference Books in C++ Programming, Data Structures and Algorithms.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn