Generating All Permutations of a String in C

 

Objective

The objective of this program is to generate and display all possible permutations of a given string. Permutations are arrangements of the characters in the string, and this program will help in understanding recursion and backtracking in programming.

C Program Code


#include 
#include 

// Function to swap characters at position i and j
void swap(char *x, char *y) {
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

// Recursive function to generate permutations
void permute(char *str, int left, int right) {
    if (left == right) {
        printf("%s\n", str);
    } else {
        for (int i = left; i <= right; i++) {
            swap((str + left), (str + i)); // Swap for the next permutation
            permute(str, left + 1, right);  // Recur
            swap((str + left), (str + i));  // Backtrack to the original string
        }
    }
}

int main() {
    char str[100];
    printf("Enter a string: ");
    scanf("%s", str);
    int n = strlen(str);
    printf("All permutations of the string are:\n");
    permute(str, 0, n - 1);
    return 0;
}

Program Structure

The program consists of the following main components:

  • Swap Function: This function swaps two characters in the string, which is essential for generating permutations.
  • Permute Function: This recursive function generates permutations by swapping characters. It calls itself to handle the next position in the string, and backtracks after each permutation is printed.
  • Main Function: This is the entry point of the program where the user inputs a string, and the permutation process is initiated.

How to Run the Program

  1. Copy the provided C code into a text editor and save it with a .c extension, for example, permutations.c.
  2. Open a terminal or command prompt.
  3. Navigate to the directory where the file is saved.
  4. Compile the program using a C compiler (e.g., gcc permutations.c -o permutations).
  5. Run the compiled program using ./permutations (on Unix/Linux) or permutations.exe (on Windows).
  6. Enter a string when prompted, and the program will display all permutations of that string.

 

One Reply to “Generating All Permutations of a String in C”

Leave a Reply

Your email address will not be published. Required fields are marked *