Program opened below. You can scroll through the algorithm, Java code and output.

Anagrams

Download .java

Question

Accept two words and determine whether they are anagrams, ignoring case.

Step 1: Start the program and accept two words. Step 2: Convert both words to the same case for case-insensitive comparison. Step 3: If their lengths differ, mark them as not anagrams. Step 4: For each character in the first word, initialise two occurrence counters. Step 5: Count the occurrences of that character in the first word using a loop. Step 6: Count its occurrences in the second word using another loop. Step 7: Compare the two occurrence counts. Step 8: If the counts differ, mark the words as not anagrams. Step 9: Continue checking the remaining characters while the words may still be anagrams. Step 10: If all counts match, classify the words as anagrams. Step 11: Display the result and stop.
Java
import java.util.*;
class AnagramCheck
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter first word: ");
        String a = sc.next().toUpperCase();
        System.out.print("Enter second word: ");
        String b = sc.next().toUpperCase();
        boolean ok = a.length() == b.length();
        for (int i = 0; i < a.length() && ok; i++)
        {
            char ch = a.charAt(i);
            int c1 = 0, c2 = 0;
            for (int j = 0; j < a.length(); j++) if (a.charAt(j) == ch)
            {
                c1++;
            }
            for (int j = 0; j < b.length(); j++) if (b.charAt(j) == ch)
            {
                c2++;
            }
            if (c1 != c2)
            {
                ok = false;
            }
        }
        if (ok)
        {
            System.out.println("Anagrams");
        }
        else
        {
            System.out.println("Not anagrams");
        }
    }
}
Input: Input: LISTEN; SILENT Output: Anagrams
← Previous Program 56 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.