In: Computer Science
C programing.
Ask user to enter a word on sting and print all possible
combinations. (please don't use printer) Using recursion.
example
ask user to input
user: "ABC"
output:
ABC
ACB
BAC
BCA
CAB
CBA
#include <stdio.h>
#include <string.h>
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *x, int l, int r)
{
int i;
if (l == r)
printf("%s\n", x);
else
{
for (i = l; i <= r; i++)
{
swap((x+l), (x+i));
permute(x, l+1, r);
swap((x+l), (x+i)); //backtrack
}
}
}
int main()
{
char str[20];
printf("Please enter a word: ");
scanf("%s",str);
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
* The order may be different but all the possible combinations will be printed.