Search This Blog

Saturday, 29 November 2014

Program in C for the Permutations of a String

Problem :- Write a program in C to print all the permutations of a String.

Solution:-



#include <stdio.h>
#include<string.h>
/* Function to print permutations takes three parameters:-(String, Starting index, Ending index) */
void permutation(char *arr, int i, int n)
{
    int j;
    if (i == n)
    {
        if(strlen(arr)==n)
        {
            printf("%s\n", arr);
        }
    }
    else
    {
        for (j = i; j <= n; j++)
        {
            swap((arr+i), (arr+j));
            permutation(arr, i+1, n);
            swap((arr+i), (arr+j));
        }
    }
}
void swap (char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
int main()
{
    char arr[100];
    gets(arr);
    int len=strlen(arr);
    permutation(arr, 0, len);
    getchar();
    return 0;
}


No comments:

Post a Comment