Hey everyone, I'm new to programming and I'm having difficulty with swapping strings now. I've to come up with a program that repeatedly prompts the user to enter a word until he types GO, which terminates the loop and causes the program to print out all possible permutations of the words entered. The execution trace should look like this:
Enter a word: many
Enter a word: dogs
Enter a word: jump
Enter a word: GO
many dogs jump
many jump dogs
....
I used recursion to solve this, and the idea for the recursion I'm using is from this link:
Write a program to print all permutations of a given string - GeeksforGeeks
Here is my code:
Code:
#include <stdio.h>#include <string.h>
void permute ( char input[][20], int index, int end );
void swap ( char *x, char *y );
int main()
{
char input [100][20] = {""}, ch;
int n = 0, index = 0, a = 0;
printf("Enter a word: ");
while ( ( ch = getchar () ) != '\n' )
{
input [0][a] = ch;
a++;
}
while ( strcmp ( input [n] , "GO" ) != 0 )
{
a = 0;
n++;
printf("Enter a word: ");
while ( ( ch = getchar () ) != '\n' )
{
input [n][a] = ch;
a++;
}
}
permute ( input, index, n - 1 );
return 0;
}
void permute ( char input[][20], int index, int end )
{
if ( index == end )
{
printf("%s\n", input [index] );
return;
}
else
{
for ( int i = index; i <= end; i++ )
{
swap ( input [i], input [i+1]);
permute ( input, index + 1, end );
swap ( input [i], input [i+1] );
}
}
}
void swap ( char *x, char *y )
{
char temp [20] = {""};
strcpy ( temp, x );
strcpy ( x, y );
strcpy ( y, temp );
}
Here is my execution trace:
Enter a word: manyEnter a word: words
Enter a word: jump
Enter a word: GO
many
GO
jump
GO
words
jump
------------------
(program exited with code: 0)
Press any key to continue . . .
Terminate batch job (Y/N)?
I don't know why it does not work, I've tried using gdb to debug using the backtrace function, but I get a No Stack message.
Can someone help me out here? I've been stuck for hours. Thanks!