View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Anagram Program in C: Different Approaches to Code

Updated on 14/05/20254,016 Views

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. 

What is an Anagram Program in C?

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:

  • They contain exactly the same characters.
  • Each character appears the same number of times in both strings.
  • The order of characters doesn’t matter.

For example:

  • "race" and "care" → Anagram
  • "hello" and "bello" → Not anagram
  • "triangle" and "integral" → Anagram

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:

  • Case sensitivity (usually converted to lowercase or uppercase).
  • Ignoring whitespaces if necessary.
  • Handling different string lengths efficiently.

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: 

Algorithm of the Anagram String in C

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.

1. Algorithm for Anagram Program in C Using Nested “For” Loops

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:

  • Search for the same character in the second string.
  • If found, mark that character as used (e.g., set to `'\0'`).
  • If not found, they are not anagrams.

5. If all characters get matched, the strings are anagrams.

2. Algorithm for Anagram Program in C Using Sorting

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.

3. Algorithm for Anagram Program in C Using Character Frequency

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.

How To Implement Anagram Program in C

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.

Key Points Before Coding Any Anagram Program in C

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.

Anagram Program in C Using Nested “For” Loop

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:

  • We take two input strings and convert them to lowercase for a fair comparison.
  • We use a nested loop to compare each character of the first string with every character of the second.
  • If a match is found, we mark that character in the second string as used.
  • If any character is not found, the strings are declared not to be anagrams.
  • This version of the anagram program in C is best suited for small strings due to its O(n²) time complexity.

Anagram Program in C To Sort the String

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:

  • Both input strings are converted to lowercase for case-insensitive comparison.
  • The `sortString` function uses a simple bubble sort to arrange characters alphabetically.
  • After sorting, we compare both strings using `strcmp`.
  • If they are identical, they are anagrams.

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.

Anagram Program in C Using a User-Defined Function

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:

  • The function `isAnagram` encapsulates the logic for checking anagrams.
  • It calls `sortString` to alphabetically arrange both strings.
  • It compares the sorted strings using `strcmp`.
  • If they match, the function returns 1 (true); otherwise, 0 (false).

This version of the anagram program in C promotes modular design and makes your code easier to read, test, and extend.

Anagram Program in C Using the Frequency of Characters

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:

  • Each character is converted to lowercase and counted in a frequency array.
  • Two arrays are used—one for each string.
  • The final comparison checks whether both arrays are identical.

This version of the anagram program in C runs in linear time (O(n)), making it the most performance-friendly approach.

Conclusion 

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.

FAQs 

1. What is an anagram in programming?

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.

2. How does an anagram program in C differ from other languages?

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.

3. Can an anagram program be case-sensitive?

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.

4. Why is frequency counting the most efficient method for anagrams?

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.

5. How do you handle special characters when checking anagrams?

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.

6. Can we check for anagrams using a hash map in C?

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.

7. How do you optimize an anagram program for very large strings?

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.

8. How can an anagram program in C handle multithreading?

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.

9. Can we check for anagrams without using arrays in C?

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.

10. What role does sorting play in an anagram program?

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.

11. Is it possible to check for anagrams using recursion in C?

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.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.