All permutations of a string

dileepkumar235 0 Tallied Votes 173 Views Share

This program displays all possible permutations of the string entered.
say if u enter
"abc" as input string the possible permutations would be
displayed as
.........................
abc
acb
bca
bac
cab
cba
..........................

#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char a[50],st_char;
int i,j,k,n,st,ctr,main_ctr;

int fn_print()
{
 for(i=0;i<=n-2;++i)
	{
		ctr=0;  /*counter for printing the string */
		printf("\n");
		printf("%c",a[0]);
		for(j=i+1;j<=n-1;j++)
			{
				printf("%c",a[j]);
				ctr++;
			}

	if(ctr!=n-1)
	while(ctr!=n-1)
		{
			st=i+1;
			for(k=1;k<=st-1;k++)
			{
				printf("%c",a[k]);
				ctr++;
			}
		}
	}
st_char=a[0];
for(i=0;i<=n-2;i++)
a[i]=a[i+1];

a[n-1]=st_char;

main_ctr++;



}

void main()
{

printf("Enter the string : ");
gets(a);

n=strlen(a);

while(main_ctr<n)
fn_print();


getch();
}
ddanbe 2,724 Professional Procrastinator Featured Poster

Nice. But why make your a string global? Why not pass it to your fn_print() function! It would make it more portable.

dileepkumar235 -5 Newbie Poster
#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int main_ctr,n;

int fn_print(char *a)
{
 char st_char;
 int i,j,k,st,ctr;
 for(i=0;i<=n-2;++i)
    {
        ctr=0;  /*counter for printing the string */
        printf("\n");
        printf("%c",a[0]);
        for(j=i+1;j<=n-1;j++)
            {
                printf("%c",a[j]);
                ctr++;
            }

    if(ctr!=n-1)
    while(ctr!=n-1)
        {
            st=i+1;
            for(k=1;k<=st-1;k++)
            {
                printf("%c",a[k]);
                ctr++;
            }
        }
    }
st_char=a[0];
for(i=0;i<=n-2;i++)
a[i]=a[i+1];
a[n-1]=st_char;
main_ctr++;
}

void main()
{
char a[50];
clrscr();
printf("Enter the string : ");
gets(a);
n=strlen(a);
while(main_ctr<n)
fn_print(a);
getch();
}
dileepkumar235 -5 Newbie Poster

i have changed the global variables and even used pointer for string processing....thanks ddanbe :)

dileepkumar235 -5 Newbie Poster

thanks for the feedback.. i ve made the modification suggested.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.