Pages

Tuesday

Program to Generate Permutation of String in C | C Program

Here's a C program to generate permutations of a string with output. This program makes use of C concepts like Array, For loopIF-Else ConditionRecursion and String Functions like string copy (strcpy()) and string length (strlen()) functions etc.


# include <stdio.h>
# include <conio.h>
# include <string.h>
void main()
{
  int n, i, k = 0 ;
  char a[10] ;
  void perm(char a[10], int k, int n) ;
  clrscr() ;
  printf("Enter the string : ") ;
  scanf("%s", a) ;
  printf("\nThe permutation is :\n") ;
  n = strlen(a) ;
  perm(a, k, n) ;
  getch() ;
}
void perm(char a[10], int k, int n)
{
  char t, d[10] ;
  int i ;
  if(k == n)
  {
    printf("\n%s", a) ;
    return ;
  }
  else
  {
    for(i = k ; i < n ; i++)
    {
      t = a[i] ;
      a[i] = a[k] ;
      a[k] = t ;
      strcpy(d, a) ;
      perm(d, k + 1, n) ;
    }
  }
} 

Output of above program

Enter the string : abc
The permutation is :
abc
acb
bac
bca
cab
cba

4 comments:

  1. so long...try this
    #include
    #include
    #include
    #include
    main()
    {
    char ch[10],temp;
    int i,k=1,b,f;
    clrscr();
    printf("enter the string");
    gets(ch);
    for(i=1;i<=strlen(ch);i++)
    {
    k=k*i;
    }
    f=strlen(ch);
    for(i=0;i<k;i++)
    {
    b=i%(f-1);
    temp = ch[b+1];
    ch[b+1]=ch[b];
    ch[b]=temp;
    printf("%s\n",ch);
    }
    getch();
    }


    ReplyDelete
  2. Thanks Chirag!! We really appreciate your participation.

    ReplyDelete
  3. chirag Agarwal's process is totally wrong.eg-when enter 1234!!! 1234 appears two times.

    ReplyDelete
  4. Hi There,


    This is indeed great! But I think perhaps you are generally referring Program to Generate Permutation of String in C | C Program which is getting unsustainable.

    I am given an assignment to write code on interpolation search binary search(searching an integer in an ordered list). but I don't have a clear idea about about both of them as I missed the theory class. so can anyone suggest me from where I can get satisfying information about them?
    I am so grateful for your blog. Really looking forward to read more.


    Kind Regards,
    Tina

    ReplyDelete