For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
If you've ever been curious about how to check if two words are anagrams using C programming, you're in the right place. In this blog, we're diving deep into the concept and implementation of the anagram program in C. Whether you're a beginner brushing up on string manipulation or an experienced coder exploring different logic techniques, this guide is designed to walk you through multiple approaches for building an efficient anagram program in C.
An anagram is a fun and intellectually stimulating concept—two strings are said to be anagrams if they contain the same characters in the same frequency but possibly in a different order. For example, "listen" and "silent" are anagrams. This seemingly simple idea can have multiple implementations when it comes to coding, and in this blog, we’ll explore how to implement an anagram program in C using various techniques. However, numerous people confuse it with string comparison in C. But, it’s completely different.
And, that’s why all the top-tier software development courses focus on this concept. By the end of this guide, you’ll not only understand how an anagram program in C works but also be able to write your own versions using loops, sorting, character frequency counts, and custom functions.
Before we dive into writing the actual anagram program in C, let’s take a moment to understand what it really means in programming terms. In simple words, an anagram program in C checks whether two given strings are anagrams of each other.
Let’s break it down further. Two strings are anagrams if:
For example:
In C programming, checking for anagrams involves comparing the characters and their frequency in both strings. A good anagram program in C will take care of:
An anagram program in C can be implemented in several ways using basic C constructs such as arrays, loops, functions, and standard library functions like `strlen()`, `tolower()`, etc.
In this blog, we’ll walk through multiple versions of the anagram program in C, starting with the core logic and expanding into optimized methods. Understanding these implementations will improve your grip on string handling, character arrays, and data manipulation in C.
Create a clear high-paying career path with the following full-stack development courses:
In C programming, there are several ways to implement an anagram program in C. Each method has its own algorithmic approach depending on whether we use loops, sorting, or frequency counting. Below, we break down the algorithms for the three most common methods used to build a reliable anagram program in C.
This is the most basic method and relies on manually matching characters from both strings using nested loops. To understand this algorithm efficiently, you should learn about the for loop in C, and nested loop in C.
Steps:
1. Take two input strings.
2. Check if their lengths are equal.
3. Convert both strings to the same case (optional).
4. For each character in the first string:
5. If all characters get matched, the strings are anagrams.
In this method, we sort both strings and then compare them. For this algorithm, it’s recommended to explore heap sort in C, and bubble sort in C.
Steps:
1. Take two input strings.
2. Check if their lengths are equal.
3. Convert both strings to the same case (optional).
4. Sort both strings using any sorting method (e.g., bubble sort or `qsort`).
5. Compare the sorted strings character by character.
6. If all characters get matched, the strings are anagrams.
This is the most efficient method, especially for larger strings. It uses frequency counting. For better understanding, you should explore arrays in C.
Steps:
1. Take two input strings.
2. Check if their lengths are equal.
3. Convert both strings to the same case (optional).
4. Create two arrays (e.g., `count1[256]` and `count2[256]`) to store the frequency of characters.
5. Traverse both strings and update the corresponding frequency arrays.
6. Compare the two frequency arrays.
7. If both arrays are identical, the strings are anagrams.
Each of these methods will be demonstrated in upcoming sections of this blog. Understanding their algorithms gives you the foundation to write any anagram program in C efficiently and with confidence.
Now that you understand the core algorithms, it's time to implement an anagram program in C using real code. The beauty of C is that it allows us to explore logic deeply and manage memory and characters precisely. In this section, we’ll walk through multiple implementations of the anagram program in C, starting from basic to more optimized methods.
Before diving into code, ensure the following setup is ready:
We will implement the anagram program in C using these techniques:
1. Using a nested `for` loop.
2. By sorting the strings and comparing.
3. Using a character frequency array.
Each method of the anagram program in C has its pros and cons, and we’ll highlight those in the explanations to help you decide which method best fits your use case.
This is one of the most straightforward ways to implement an anagram program in C. It compares each character in the first string with every character in the second string using a nested loop. It’s not the most efficient for large strings, but it's great for understanding the core logic behind checking anagrams manually.
Code Example:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str1[100], str2[100];
int i, j, len1, len2, found;
char temp[100];
// Taking input from the user
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
// Converting both strings to lowercase to ensure case-insensitive comparison
for(i = 0; str1[i]; i++) str1[i] = tolower(str1[i]);
for(i = 0; str2[i]; i++) str2[i] = tolower(str2[i]);
len1 = strlen(str1);
len2 = strlen(str2);
// If lengths differ, they can't be anagrams
if(len1 != len2) {
printf("Strings are not anagrams.\n");
return 0;
}
// Copy second string into temp array to modify it
strcpy(temp, str2);
// Comparing characters using nested loop
for(i = 0; i < len1; i++) {
found = 0;
for(j = 0; j < len2; j++) {
if(str1[i] == temp[j]) {
temp[j] = '*'; // Mark character as used
found = 1;
break;
}
}
if(!found) {
printf("Strings are not anagrams.\n");
return 0;
}
}
// If all characters matched
printf("Strings are anagrams.\n");
return 0;
}
Sample Output:
Enter first string: Race
Enter second string: Care
Strings are anagrams.
Explanation:
Sorting is a popular and more efficient way to check for anagrams. In this method, we sort both strings alphabetically and compare them. If the sorted strings are identical, then the original strings are anagrams. This version of the anagram program in C improves performance, especially when working with larger strings, by reducing the comparison logic to a simple `strcmp`.
Code Example:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// Function to sort characters of a string using bubble sort
void sortString(char *str) {
int i, j;
char temp;
int len = strlen(str);
for(i = 0; i < len - 1; i++) {
for(j = i + 1; j < len; j++) {
if(str[i] > str[j]) {
// Swap characters
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
int main() {
char str1[100], str2[100];
// Input from user
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
// Convert both strings to lowercase
for(int i = 0; str1[i]; i++) str1[i] = tolower(str1[i]);
for(int i = 0; str2[i]; i++) str2[i] = tolower(str2[i]);
// Check if lengths are equal
if(strlen(str1) != strlen(str2)) {
printf("Strings are not anagrams.\n");
return 0;
}
// Sort both strings
sortString(str1);
sortString(str2);
// Compare sorted strings
if(strcmp(str1, str2) == 0)
printf("Strings are anagrams.\n");
else
printf("Strings are not anagrams.\n");
return 0;
}
Sample Output:
Enter first string: Listen
Enter second string: Silent
Strings are anagrams.
Explanation:
This version of the anagram program in C is cleaner and more efficient than the nested loop approach. It’s especially useful when comparing long strings and when readability matters.
Modular programming is a good practice in C, and using functions helps make code more reusable and organized. In this version of the anagram program in C, we’ll create a user-defined function to check whether two strings are anagrams. This makes the main logic reusable across different parts of a larger program.
Code Example:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// Function to sort a string
void sortString(char *str) {
int i, j;
char temp;
int len = strlen(str);
for(i = 0; i < len - 1; i++) {
for(j = i + 1; j < len; j++) {
if(str[i] > str[j]) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
// Function to check if two strings are anagrams
int isAnagram(char str1[], char str2[]) {
// Convert both strings to lowercase
for(int i = 0; str1[i]; i++) str1[i] = tolower(str1[i]);
for(int i = 0; str2[i]; i++) str2[i] = tolower(str2[i]);
// Check lengths first
if(strlen(str1) != strlen(str2)) {
return 0;
}
// Sort both strings
sortString(str1);
sortString(str2);
// Compare sorted strings
return strcmp(str1, str2) == 0;
}
int main() {
char str1[100], str2[100];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
if(isAnagram(str1, str2))
printf("Strings are anagrams.\n");
else
printf("Strings are not anagrams.\n");
return 0;
}
Sample Output:
Enter first string: heart
Enter second string: earth
Strings are anagrams.
Explanation:
This version of the anagram program in C promotes modular design and makes your code easier to read, test, and extend.
This is the most efficient method to implement an anagram program in C, especially when dealing with large strings. Instead of sorting or using nested loops, this approach leverages character frequency. The idea is simple: if two strings are anagrams, the frequency of every character must be the same in both strings.
We use arrays of size 256 (to cover all ASCII characters) to count the frequency of characters in each string.
Code Example:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int isAnagram(char str1[], char str2[]) {
int count1[256] = {0}; // Frequency array for first string
int count2[256] = {0}; // Frequency array for second string
int i;
// Convert strings to lowercase and update frequency arrays
for(i = 0; str1[i] != '\0'; i++) {
count1[tolower(str1[i])]++;
}
for(i = 0; str2[i] != '\0'; i++) {
count2[tolower(str2[i])]++;
}
// Compare frequency arrays
for(i = 0; i < 256; i++) {
if(count1[i] != count2[i]) {
return 0; // Not anagram
}
}
return 1; // Anagram
}
int main() {
char str1[100], str2[100];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
// Compare string lengths first (early exit for unequal lengths)
if(strlen(str1) != strlen(str2)) {
printf("Strings are not anagrams.\n");
return 0;
}
if(isAnagram(str1, str2))
printf("Strings are anagrams.\n");
else
printf("Strings are not anagrams.\n");
return 0;
}
Sample Output:
Enter first string: Listen
Enter second string: Silent
Strings are anagrams.
Explanation:
This version of the anagram program in C runs in linear time (O(n)), making it the most performance-friendly approach.
In this blog, we covered several methods to implement an anagram program in C, each with its strengths and trade-offs. The nested loop approach is simple but inefficient for larger strings, while the sorting method improves efficiency and readability, albeit with a higher time complexity. The most optimal solution is the frequency counting method, which runs in linear time and works best for large strings or performance-sensitive applications.
Choosing the right method depends on the size of the strings you're working with and the level of performance required. By understanding these different implementations, you can pick the most suitable approach for your specific problem. Whether you're learning C or building an application, mastering the anagram program in C gives you valuable insights into string manipulation and algorithm design.
In programming, an anagram refers to two strings that contain the same characters with the same frequency but in a different order. An anagram checker program verifies whether two input strings meet this condition by comparing their characters or sorting them. It is a fundamental problem in string manipulation algorithms.
An anagram program in C is quite similar to implementations in other languages. However, C gives you more control over memory and string manipulation, making it more flexible but also requiring more manual work. Other languages like Python or Java offer higher-level functions for string handling, making anagram checking easier and more concise.
Yes, an anagram program can be case-sensitive, but it’s typically case-insensitive to ensure that, for example, "Listen" and "silent" are recognized as anagrams. If you want a case-sensitive check, you simply omit the conversion of characters to lowercase before comparing the strings, ensuring that only exact matches are considered.
Frequency counting is the most efficient method for checking anagrams because it operates in linear time, O(n). This method counts the occurrences of each character in the strings and then compares the counts. It avoids the overhead of sorting and nested loops, making it ideal for large strings where performance is crucial.
To handle special characters in an anagram program, you can strip out non-alphabetic characters before performing the comparison. This ensures that spaces, punctuation, and other symbols do not interfere with the anagram check. For example, "a!bc" and "cba" would be treated as anagrams after removing special characters.
Yes, a hash map can be used to check for anagrams in C by using the ASCII values of characters as keys. The hash map stores the frequency of each character for both strings, and a comparison of the two hash maps determines whether the strings are anagrams. This method combines frequency counting with efficient lookups.
To optimize an anagram program for very large strings, you should use the character frequency method. By maintaining a frequency array and processing each character of the strings once, this approach has a time complexity of O(n), which is much more efficient than sorting or nested loops for large data sets.
An anagram program in C can handle multithreading by dividing the task of comparing characters across multiple threads. For instance, one thread could count the frequency of characters in one string, while another thread processes the second string. Using thread synchronization mechanisms ensures that results are combined accurately and efficiently.
Yes, you can check for anagrams without using arrays by utilizing dynamic data structures like hash tables. Instead of using fixed-size arrays to store character frequencies, you can dynamically allocate space for the characters you encounter and keep track of their counts. This allows for more flexibility, especially with larger or varied input.
Sorting plays a key role in an anagram program by rearranging the characters of both strings in a standard order (alphabetical or lexicographical). Once both strings are sorted, comparing them becomes a simple task of checking if the sorted versions are identical. Sorting helps simplify the anagram checking process but can be slower for large strings.
Yes, it is possible to check for anagrams using recursion in C. One approach could involve recursively comparing characters from both strings while reducing the problem size after each recursive call. However, recursion may not always be the most efficient method, especially for large strings due to increased memory usage and stack overflow risks.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Previous
Next
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.