Permutation of String in C and C++

Here you will get the program for the stage of string in C and C++.

Stage implies every conceivable plan of a given arrangement of numbers or characters. For a string with n characters can have complete n! courses of action.

Program for Permutation of String in C

#include <stdio.h>
#include <string.h>
 
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
 
void permutation(char *a, int l, int r)
{
   int i;
   
   if (l == r)
     printf("%s\n", a);
   else
   {
       for (i = l; i <= r; i++)
       {
          swap((a+l), (a+i));
          permutation(a, l+1, r);
          swap((a+l), (a+i));
       }
   }
}
 
int main()
{
    char string[20];
    int n;
    
    printf("Enter a string: ");
    scanf("%s", string);
    
	n = strlen(string);
    permutation(string, 0, n-1);
    
	return 0;
}

Output-

Enter a string: abc
abc
acb
bac
bca
cba
cab

Program for Permutation of String in C++

#include <iostream>
#include <string.h>
 
using namespace std;
 
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
 
void permutation(char *a, int l, int r)
{
   int i;
   
   if (l == r)
     cout << a << "\n";
   else
   {
       for (i = l; i <= r; i++)
       {
          swap((a+l), (a+i));
          permutation(a, l+1, r);
          swap((a+l), (a+i));
       }
   }
}
 
int main()
{
    char string[20];
    int n;
    
    cout << "Enter a string: ";
    cin >> string;
    
	n = strlen(string);
    permutation(string, 0, n-1);
    
	return 0;
}

Leave a Comment

error: Alert: Content is protected!!