An anagram is a word or phrase formed by rearranging all the characters of another. In C, the standard way to check if two strings are anagrams is to count character frequencies: if both strings have exactly the same character counts, they are anagrams — regardless of order.
This page shows a complete anagram program in C using the frequency-counting method, with step-by-step explanation, sample output, and time complexity analysis.
How to Check for Anagrams — Step by Step
- Check that both strings have the same length. If not, they cannot be anagrams.
- Create an integer array of size 256 (one slot per ASCII character), initialized to zero.
- Loop through the first string: increment the frequency of each character.
- Loop through the second string: decrement the frequency of each character.
- If all 256 entries are still zero, both strings have identical character counts — they are anagrams.
Example: “listen” and “silent” — both have the same characters (e, i, l, n, s, t), just in different order. After step 4, every count returns to zero. ✓ Anagram.
Anagram Program in C
#include <stdio.h>
#include <string.h>
#define CHARS 256
int isAnagram(const char *s1, const char *s2)
{
int freq[CHARS] = {0};
int i;
for (i = 0; s1[i] != '\0'; i++)
freq[(unsigned char)s1[i]]++;
for (i = 0; s2[i] != '\0'; i++)
freq[(unsigned char)s2[i]]--;
for (i = 0; i < CHARS; i++)
if (freq[i] != 0)
return 0;
return 1;
}
int main(void)
{
char s1[100], s2[100];
printf("Enter first string: ");
fgets(s1, sizeof s1, stdin);
s1[strcspn(s1, "\n")] = '\0';
printf("Enter second string: ");
fgets(s2, sizeof s2, stdin);
s2[strcspn(s2, "\n")] = '\0';
if (isAnagram(s1, s2))
printf("\"%s\" and \"%s\" are anagrams.\n", s1, s2);
else
printf("\"%s\" and \"%s\" are not anagrams.\n", s1, s2);
return 0;
}
How to Compile and Run
gcc -ansi -Wall -Wextra -o anagram anagram.c
./anagram
Sample Input and Output
Enter first string: listen Enter second string: silent "listen" and "silent" are anagrams. Enter first string: hello Enter second string: world "hello" and "world" are not anagrams.
Code Explanation
freq[CHARS]: One integer per ASCII value (0–255). The cast(unsigned char)prevents undefined behavior on platforms wherecharis signed and the character value is negative.- Two-pass approach: Increment on the first string, decrement on the second. This avoids the need for a second array and handles length mismatches automatically — a longer string will leave non-zero entries.
fgets+strcspn: Safe input reading.fgetslimits input to buffer size;strcspn(s, "\n")strips the trailing newline thatfgetsleaves in the buffer.- Final loop: If any
freq[i] != 0, the strings differ in at least one character — not anagrams.
Time and Space Complexity
| Complexity | Value | Reason |
|---|---|---|
| Time | O(n) | One pass through each string (n = length of longer string) |
| Space | O(1) | Fixed 256-element array — independent of input size |
This is optimal: you must read every character at least once (Ω(n)), and the space is constant regardless of input length.
What This Program Teaches
- Using a frequency/histogram array to compare character distributions
- Safe string input with
fgets()instead of the dangerousgets() - The
(unsigned char)cast pattern — important when indexing arrays by character value - Why single-array increment/decrement is cleaner than two separate count arrays
Related Programs
- C Program to Sort a String
- C Program to Find All Permutations of a String
- C Program to Count Occurrences of a Word in a String
- C Program to Reverse a String Using Pointers
As an Amazon Associate we earn from qualifying purchases.
Further Reading
Strings, arrays, and standard library functions like strcspn are all covered thoroughly in The C Programming Language by K&R — the definitive reference for C. Available on Amazon.com as well.
2 comments on “Anagram Program in C – Check if Two Strings are Anagrams”
I just install WordPress. I post several posts but they all proceed to homepage. How can I let posts move to different web page, for example , I have ‘articles’ tabs and ”events’ tab. I would like articles listings go to articles section and I would like events listings go to events section..
Hi Jerica,
Please share your email address or Skype id. I will contact you and help you with your problem.