Anagram Program in C – Check two strings are anagrams

Program Description:

In an earlier article, We looked at how to Swap two strings in C. In today’s article, We will look at the anagram program in c language. The program should accept two strings from the user and check if the two strings are anagrams.

📢 This Program is part of the C String Practice Programs series

What is Anagram String:

An anagram is a word or phrase that is formed by rearranging the letters of another word or phrase.

All the original word letters are used exactly once.

An example of Anagram strings are:

State and Taste.

We can create the State string by rearranging the letters of the Taste string.

📢 The program is case-insensitive(Ignore case). So the uppercase characters and lowercase characters have the same meaning. (i.e V = v )

Let’s quickly look at the example input and output of the program.

Example Input and Output:

Input:

Enter the first string : Players

Enter the second string: parsley

Output:

ANAGRAMS! Given Strings are Anagrams

We are going to look at a few methods to check if the given strings are Anagrams and Each program will be followed by a detailed step-by-step explanation and program output. Then We also provided instructions for compiling and running the program using your compiler.

We will look at three different methods to check Anagram in C, They are

  1. Standard Method – Iterative method for Anagram program in C. Uses manual process to check the anagram. (Easy and straightforward Method)
  2. Using User-defined function – We are going to use a user-defined function to check the anagram.
  3. Advanced Method – In this method, We track the frequency of each character and check the anagram. ( Recommended Method)

Let’s look at each method in detail.

Algorithm for Anagram Program in C – Standard Method:

  1. Take two input strings from the user and read the strings using the gets function. Let the input strings as firstStr and secondStr
  2. Calculate the length of each string using the strlen() function and store the string lengths in len1 and len2 respectively.
  3. Check if the len1 and len2 are equal, If the two strings’ lengths are not equal, Then they are not anagrams. So display the error message and stop the program using return statement.
  4. As the program is case-insensitive, We need to convert the input strings to either lowercase or uppercase. We are converting the strings to lowercase using a custom strLower() function.
  5. Call the strLower() function with two strings firstStr and secondStr.
  6. Once the above step 5 is completed, Two strings will be in Lower case. It will ease up our comparison.
  7. Now, We need to sort the strings. We are using the qsort() function from stdlib.h library. Call the qsort() function with each string to sort the strings in ascending order.
  8. Once the above operation is completed, The two strings will be sorted in ascending order. Now we need to Compare the firstStr and secondStr strings.
    • We are using the strcmp library function to compare the strings. Call the strcmp function with two strings firstStr and secondStr.
  9. If the strcmp() function returns Zero(0), Then the two strings firstStr and secondStr are Anagrams. Otherwise, Strings are Not Anagrams.
  10. Display the result on the console.

Standard Method: Program to Check two strings are Anagrams in C:

Let’s convert the above algorithm into the C program which will check if the two strings are anagrams.

We have added extensive comments to the program for your convenience.

We are using three extra header files, string.h, ctype.h, and stdlib.h header files.

Program Output:

Let’s compile and run the program using GCC compiler (Any compiler)

Test case 1:

Provide two strings and check if they are anagrams

Program-to-Check-two-strings-are-Anagrams-in-C-standard-method

We can form the car string by rearranging the characters of the arc string, So the given strings arc and car are anagrams.

The input strings listen and Silent are anagrams, So the program properly calculated and displayed the strings as anagrams.

Test Case 2: Two Word Anagrams or Check if the phrases are anagrams.

As we can see from the above output, The program is able to check the anagrams of phrases or sentences. The Given phrases the eyes and They See are Anagrams.

Test Case 3: Negative Case

In this example, We have provided the strings as programming and learn. As we can see these two strings are of different length and doesn’t form the other string, So they are Not Anagrams.

Anagram Program in C using user-defined functions:

In the above program, We have used two custom functions like strLower and compare but the logic to check anagram strings is written inside the main function. So let’s move this code to a separate function So that we can simply call the check anagram function from the main() function.

By using the functions we can define a function once and can call it as many times as we want. Functions also increase the readability of the program and make it easier to debug issues. Here are the benefits using the functions in programming.

Here is the rewritten version of the anagram program in C. In this program, We defined a custom function called isAnagram to check anagram strings.

The prototype of the isAnagram() function is

int isAnagram(char * firstStr, char * secondStr);

This function takes two strings as formal arguments, They are firstStr and secondStr. It checks if the given strings are Anagrams.

The isAnagram() function returns One(1) if the two strings are Anagrams, Otherwise, it returns Zero(0).

Program Output:

Compile and Run the program.

anagram-program-using-user-defined-function

As we can see from the above output, The isAnagram function is properly checking the anagrams.

Algorithm for Anagram Program in C – Advanced Method:

Now, Let’s look at another method, Where we use the character frequencies to check if the two strings are anagrams.

Here is the algorithm of the Anagram program in C (Advanced Method)

  1. Take two strings from the user and Convert them to lowercase using the custom strLower() function.
  2. Inside the isAnagram() function, Create a frequency array with the ASCIISIZE(256) to store the frequencies of each character in strings.
  3. Then, Traverse through the two strings and update the frequency array. – Loop should look like this for(i=0; firstStr[i] && secondStr[i]; i++)
    • Increment character frequency for the first string (firstStr)
    • Decrement the character frequency for the second string (secondStr)
  4. Check if any of the string is not reached the NULL, Which means the two strings’ lengths are different. So the strings are not anagrams. Return Zero(0).
  5. Then, Go through the frequency array and check if any character frequency is greater than zero. This means The characters from two strings are not matched, So the strings are not anagrams. If we found any character with greater than zero frequency (>0), Then Strings are not anagrams. Return Zero(0).
  6. If we iterated over the frequency array successfully and not found any mismatch, Then the given strings firstStr and secondStr are Anagrams. Return One(1).
  7. Call the isAnagram() function from the main function and pass the two input strings. and display the results.

Advanced Method to Check Anagrams in C Langauge:

Here is the program to check two strings are anagrams in the C programming language.

Program Output:

Let’s compile and Run the above program.

anagram-program-in-c-with-program-output

As we can see from the above output, The two input sentences School Master and The Classroom are Anagram strings.

The strings Active and Passive are not anagrams. The program is properly detecting the anagram strings.

Related Programs:

Venkatesh

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

1 Response

  1. […] Anagram Program in C – Check two strings are anagrams […]

Leave a Reply