SUNDAY, 12 JULY 2026
Guide For School logo Guide For SchoolStudy Guide For Students On Java Programming
Physics | Chemistry | Mathematics
ICSE | ISC | CBSE
Guide For School logo Guide For SchoolICSE and ISC Resources

Anagrams of a Word Program in Java and Python

07 August 2015

Anagrams of a word program with algorithm, explanation, Java recursion solution and simple Python solution for ICSE and ISC students.

Question:

Write a program to input a word and print its anagrams. Anagrams are words formed by rearranging all the characters of the original word. For example, anagrams of TOP are TOP, TPO, OPT, OTP, PTO and POT.

INPUT: Enter a word: BACK OUTPUT: The Anagrams are: BACK BAKC BCAK BCKA BKAC BKCA ... Total Number of Anagrams = 24

Algorithm:

Step 1: Start.

Step 2: Accept the word as input.

Step 3: Convert the word into a character array or string that can be rearranged.

Step 4: Call the anagram method with the first index as the fixed position.

Step 5: If the fixed position reaches the last character, display the current arrangement and increment the counter.

Step 6: Otherwise, run a loop from the fixed position to the last index.

Step 7: Swap the character at the fixed position with the loop index.

Step 8: Recursively call the method for the next fixed position.

Step 9: Swap the characters back to restore the previous arrangement before the next loop cycle.

Step 10: After recursion ends, display the total counter value.

Step 11: Stop.

Explanation:

The anagram program uses recursion and swapping. At each recursive level, one position of the word is fixed and the remaining positions are rearranged.

The loop chooses which character should be placed at the current fixed index. After choosing it, the method calls itself for the next index.

When the fixed index reaches the last character, one complete arrangement has been formed. The program prints that arrangement and increments the counter.

The swap-back step is essential. It restores the word to its previous order before the loop tries the next character at the same position.

The counter variable records how many arrangements have been printed. For a word with unique letters, this count becomes factorial of the number of characters.

The deeper idea in this program is systematic generation. An anagram is not found by guessing; the program fixes one character at a position and then rearranges the remaining characters around it. This naturally leads to repeated swapping or recursive-style arrangement logic. The important teaching point is that every position must get a chance to hold every character, while the remaining positions are handled in the same manner. Care is also needed to restore the word after a swap so that later arrangements are not affected by earlier ones.

Java Program:

Java
/**
* The class Anagrams inputs a word and generates its anagrams
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.util.*;
class Anagrams
{
    int c = 0;

    void input()throws Exception
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word : ");
        String s = sc.next();
        System.out.println("The Anagrams are : ");
        display("",s);
        System.out.println("Total Number of Anagrams = "+c);
    }

    void display(String s1, String s2)
    {
        if(s2.length()<=1)
        {
            c++;
            System.out.println(s1+s2);
        }
        else
        {
            for(int i=0; i<s2.length(); i++)
            {
                String x = s2.substring(i, i+1);
                String y = s2.substring(0, i);
                String z = s2.substring(i+1);
                display(s1+x, y+z);
            }
        }
    }

    public static void main(String args[])throws Exception
    {
        Anagrams ob=new Anagrams();
        ob.input();
    }
}

Equivalent Python Program:

Python
# Read the text input and split or scan it according to the question requirement.
# Helper functions keep repeated calculations separate from the main logic.
# Loops process each word/character and update counters or result strings.
# Display the final text result after sorting, checking or rearranging is complete.

count = 0

def swap(chars, i, j):
    temp = chars[i]
    chars[i] = chars[j]
    chars[j] = temp

def anagram(chars, fixed):
    global count
    if fixed == len(chars) - 1:
        print("".join(chars))
        count = count + 1
    else:
        for i in range(fixed, len(chars)):
            swap(chars, fixed, i)
            anagram(chars, fixed + 1)
            swap(chars, fixed, i)

word = input("Enter a word: ")
chars = []
for i in range(len(word)):
    chars.append(word[i])
print("The Anagrams are:")
anagram(chars, 0)
print("Total Number of Anagrams =", count)

Output:

INPUT: Enter a word: BACK OUTPUT: The Anagrams are: BACK BAKC BCAK BCKA BKAC BKCA ... Total Number of Anagrams = 24

Leave a Reply

Your email address will not be published. Comments are reviewed before appearing publicly.

Send a comment or correction

Study smarter

Everything you need for ICSE and ISC Computer

Programs, revision notes, solved papers and practical guidance—organized for quick study.

Browse all resources →