What is an anagram in C language?

Anagram strings are nothing but, all the characters that occur for the same number of times in another string, which we call as anagrams.

A user enters two strings. We need to count how many times each letter ('a' to 'z') appears in them and then, compare their corresponding counts. The frequency of an alphabet in a string is how many times it appears in it.

If two strings have same count of the frequency of particular alphabet then, we can say those two strings are anagrams.

Example 1

String 1 − abcd

String 2 − bdac

These two strings have same letters which appear once. So, these two strings are anagrams.

Example 2

String 1 − programming

String 2 − gramming

Output − The strings are not anagrams.


Following is the C program for an anagram −

#include <stdio.h>
int check_anagram(char [], char []);
int main(){
   char a[1000], b[1000];
   printf("Enter two strings
");    gets(a);    gets(b);    if (check_anagram(a, b))       printf("The strings are anagrams.
");    else       printf("The strings aren't anagrams.
");       return 0; } int check_anagram(char a[], char b[]){    int first[26] = {0}, second[26] = {0}, c=0;    // Calculating frequency of characters of the first string    while (a[c] != '\0') {       first[a[c]-'a']++;       c++;    }    c = 0;    while (b[c] != '\0') {       second[b[c]-'a']++;       c++;    }    // Comparing the frequency of characters    for (c = 0; c < 26; c++)    if (first[c] != second[c])       return 0;       return 1; }


When the above program is executed, it produces the following output −

Run 1:
Enter two strings
The strings are anagrams.
Run 2:
Enter two strings
The strings aren't anagrams.