
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
All permutations of a string using iteration?
In this section we will see how to get all permutations of a string. The recursive approach is very simple. It uses the back-tracking procedure. But here we will use the iterative approach.
All permutations of a string ABC are like {ABC, ACB, BAC, BCA, CAB, CBA}. Let us see the algorithm to get the better idea.
Algorithm
getAllPerm(str)
begin sort the characters of the string while true, do print the string str i := length of str – 1 while str[i - 1] >= str[i], do i := i – 1 if i is 0, then return end if done j := length of str – 1 while j > i AND str[j] <= str[i – 1], do j := j – 1 done exchange the characters from position str[i - 1], str[j] reverse the string. done end
Example
#include <iostream> #include <algorithm> using namespace std; void getAllPerm(string str){ sort(str.begin(), str.end()); while (true){ cout << str << endl; int i = str.length() - 1; while (str[i-1] >= str[i]){ if (--i == 0) return; } int j = str.length() - 1; while (j > i && str[j] <= str[i - 1]) j--; swap(str[i - 1], str[j]); reverse (str.begin() + i, str.end()); } } int main(){ string str = "WXYZ"; getAllPerm(str); }
Output
WXYZ WXZY WYXZ WYZX WZXY WZYX XWYZ XWZY XYWZ XYZW XZWY XZYW YWXZ YWZX YXWZ YXZW YZWX YZXW ZWXY ZWYX ZXWY ZXYW ZYWX ZYXW
- Related Articles
- Print all permutations of a given string
- Print all permutations of a string in Java
- Print all palindrome permutations of a string in C++
- Python Program to Print All Permutations of a String in Lexicographic Order using Recursion
- C++ Permutations of a Given String Using STL
- Python Program to print all permutations of a given string
- C Program to print all permutations of a given string
- Creating all possible unique permutations of a string in JavaScript
- Python program to get all permutations of size r of a string
- Print all distinct permutations of a given string with duplicates in C++
- How to find all possible permutations of a given string in Python?
- Golang program to compute all the permutations of the string
- Check if a binary string contains all permutations of length k in C++
- All reverse permutations of an array using STL in C++?
- Python Program to Print All Permutations of a String in Lexicographic Order without Recursion

Advertisements