Table of contents
1.
Introduction
2.
What is Anagram in String?
3.
Algorithm of the Anagram String
4.
Example 1: Program to Check the Anagram of the String Using User-Defined Function
4.1.
Implementation
4.2.
C
5.
Example 2: Program to Check the Anagram of the String Using Nested For Loop
5.1.
Implementation
5.2.
C
6.
Example 3: Program to Check the Anagram of the String Using For and If Statements
6.1.
Implementation
6.2.
C
7.
Example 4: Program to Sort the String and Check the Anagram of the Strings
7.1.
Implementation
7.2.
C
8.
Frequently Asked Questions
8.1.
What is an anagram?
8.2.
Why sort strings in an anagram-checking program?
8.3.
Can this anagram-checking approach be used with phrases?
8.4.
How to check if word is anagram in C?
9.
Conclusion
Last Updated: Oct 21, 2024
Easy

Anagram Program in C

Author Ravi Khorwal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Anagrams are words or phrases that can be formed by rearranging the letters of another word or phrase. For example, "listen" & "silent" are anagrams because they contain the same letters. Checking if two strings are anagrams is a common programming problem that helps beginners understand string manipulation. 

Anagram Program in C

In this article, we'll learn different ways to solve the anagram problem using C programming language. We'll cover various algorithms & provide code examples to help you grasp the concepts better.

What is Anagram in String?

An anagram is a rearrangement of the characters in a string to form another string. Two strings are anagrams if they contain the same characters in the same frequencies, regardless of their order. For example, "listen" and "silent" are anagrams because they have identical characters.

Algorithm of the Anagram String

To understand if two words are anagrams, we first need a method to compare them. In simple terms, an anagram checks if by rearranging the letters of one word, you can form another word. Here, we'll explain how you can create a program in C to perform this check.

The basic idea is to count the frequency of each letter in both words & compare these counts. If both words have the exact same number of each letter, they are anagrams; otherwise, they are not. Let's look into the steps:

  • Initialize Count Arrays: We start by creating two arrays to count the frequency of each letter for the two words.
     
  • Fill the Count Arrays: Loop through each character in the words & increase the corresponding count in the arrays.
     
  • Compare the Count Arrays: Check if both arrays have the same values for every letter. If they match completely, the words are anagrams.

Example 1: Program to Check the Anagram of the String Using User-Defined Function

This program will use a user-defined function that makes it easier to reuse and understand the code. Here's how you can do it step by step:

  1. Function Definition: We'll start by defining a function isAnagram that takes two strings as inputs.
     
  2. Create Count Arrays: Inside the function, we initialize two arrays to store the letter counts of each string.
     
  3. Populate the Arrays: As we loop through each string, we increase the count of each character in the corresponding array.
     
  4. Compare Arrays: After counting, we compare both arrays. If they are identical in terms of frequency for every character, the strings are anagrams.
     
  5. Return the Result: The function returns true if the strings are anagrams, otherwise false.

Implementation

  • C

C

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

bool isAnagram(char *str1, char *str2) {
int count1[256] = {0}, count2[256] = {0};
int i;

for (i = 0; str1[i] && str2[i]; i++) {
count1[str1[i]]++;
count2[str2[i]]++;
}

if (str1[i] || str2[i])
return false;

for (i = 0; i < 256; i++)
if (count1[i] != count2[i])
return false;

return true;
}

int main() {
char str1[100], str2[100];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);

if (isAnagram(str1, str2))
printf("The strings are anagrams.\n");
else
printf("The strings are not anagrams.\n");

return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Enter first string: hello
Enter second string: world
The strings are not anagrams.


In this code, we ensure the strings are of equal length before checking if they are anagrams. The gets function is used for simplicity to read strings, though it's generally better to use safer alternatives in real applications.

Example 2: Program to Check the Anagram of the String Using Nested For Loop

Next, we will look at another method to determine if two strings are anagrams by using nested for loops. This method is straightforward and directly compares each character's occurrences from one string to the other. Let's see how it works step by step:

  1. Initialize Variables: First, define two strings and variables for checking conditions.
     
  2. Input Strings: Ask the user to enter two strings that they want to check.
     
  3. Use Nested Loops: Set up a loop within a loop to compare each character's occurrences between the two strings.
     
  4. Count & Compare: Inside the inner loop, check each character from the first string against all characters in the second string, counting matches.
     
  5. Final Condition Check: After looping, if all characters match the count and order, the strings are anagrams.
     

Implementation

  • C

C

#include <stdio.h>
#include <string.h>

int main() {
char str1[100], str2[100];
int len1, len2, i, j, found, not_found;

printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin);

len1 = strlen(str1) - 1; // Adjust for newline character
len2 = strlen(str2) - 1; // Adjust for newline character

if (len1 != len2) {
printf("The strings are not anagrams.\n");
return 0;
}

for (i = 0; i < len1; i++) {
found = 0;
not_found = 0;
for (j = 0; j < len2; j++) {
if (str1[i] == str2[j]) {
found = 1;
str2[j] = '\0'; // This marks the matched character as used
break;
}
}
if (!found) {
not_found = 1;
break;
}
}

if (not_found)
printf("The strings are not anagrams.\n");
else
printf("The strings are anagrams.\n");

return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Enter first string: hello
Enter second string: world
The strings are not anagrams.


In this example, if a character in str1 is found in str2, we mark it as used by setting it to \0. This helps ensure that a character is not counted more than once. This method is particularly useful for understanding how looping mechanisms work in C programming to perform character-by-character analysis of strings.

Example 3: Program to Check the Anagram of the String Using For and If Statements

Another way to determine if two strings are anagrams is by using a combination of for loops and if statements. This method is quite effective and focuses on a direct character comparison. Let's outline how to implement this:

  1. Initialize Variables: First, set up two strings and variables for length comparison and condition checking.
     
  2. Input Strings: Get two strings from the user that they wish to check against each other.
     
  3. Check Lengths: Ensure both strings are of the same length. If not, they cannot be anagrams.
     
  4. Sort Strings: Sort both strings alphabetically. This makes comparing them easier because anagrams will appear identical once sorted.
     
  5. Loop & Compare: Use a for loop to compare the sorted strings character by character.

Implementation

  • C

C

#include <stdio.h>
#include <string.h>

void sortString(char *str) {
char temp;
int i, j;
int n = strlen(str);
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (str[i] > str[j]) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}

int main() {
char str1[100], str2[100];
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin);

// Remove newline character from fgets input
str1[strlen(str1) - 1] = '\0';
str2[strlen(str2) - 1] = '\0';

sortString(str1);
sortString(str2);

if (strcmp(str1, str2) == 0)
printf("The strings are anagrams.\n");
else
printf("The strings are not anagrams.\n");

return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Enter first string: hello
Enter second string: world
The strings are not anagrams.


In this code, the sortString function rearranges the characters of the string in ascending order. Once both strings are sorted, a simple comparison using strcmp determines if they are anagrams. This method is useful for understanding both sorting algorithms and simple conditional checks in C.

Example 4: Program to Sort the String and Check the Anagram of the Strings

Our final example explores a clear method to check if two strings are anagrams by first sorting them and then comparing. This approach is practical and teaches us how sorted data can simplify comparisons. Here’s how to execute this step by step:

  1. Define the Function: We'll write a function sortAndCheckAnagram to handle the sorting and comparison.
     
  2. Sort Both Strings: The function will sort both strings alphabetically. Sorting helps in lining up characters, making it easy to compare.
     
  3. Compare Sorted Strings: After sorting, a simple string comparison determines if the two are anagrams.

Implementation

  • C

C

#include <stdio.h>
#include <string.h>

void sortString(char *str) {
char temp;
int i, j;
int n = strlen(str);
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (str[i] > str[j]) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}

int main() {
char str1[100], str2[100];
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin);

// Remove newline character from fgets input
str1[strlen(str1) - 1] = '\0';
str2[strlen(str2) - 1] = '\0';

sortString(str1);
sortString(str2);

if (strcmp(str1, str2) == 0)
printf("The strings are anagrams.\n");
else
printf("The strings are not anagrams.\n");

return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Enter first string: hello
Enter second string: world
The strings are not anagrams.


In this simple yet effective example, we sort each string individually and then perform a direct comparison. This method highlights the effectiveness of sorting as a preliminary step in data comparison, especially when dealing with anagram detection.

Frequently Asked Questions

What is an anagram?

An anagram is when two words or phrases consist of the same letters rearranged differently. For example, "listen" and "silent" are anagrams.

Why sort strings in an anagram-checking program?

Sorting strings makes it easier to compare them because anagrams will appear identical once sorted, simplifying the check to a direct comparison.

Can this anagram-checking approach be used with phrases?

Yes, but you need to remove spaces and punctuation from the phrases before checking to ensure accuracy.

How to check if word is anagram in C?

To check if two words are anagrams in C, sort both strings and compare them. If they are identical after sorting, the words are anagrams; otherwise, they are not.

Conclusion

In this article, we have learned various ways to check if two strings are anagrams in C. We started with understanding the basic concept of an anagram and progressed through different methods involving user-defined functions, nested loops, and sorting algorithms. Each example provided a practical approach, complete with code, to identify anagrams efficiently. 

You can refer to our blogs on Code360

Live masterclass