You are here

Anagram program in C

Anagram program in C: C program to check whether two strings are anagrams or not, a string is assumed to consist of lower case alphabets only. Two words are said to be anagrams of each other if the letters of one word can be rearranged to form the other word. So, in anagram strings, all characters occur the same number of times. For example, "abc" and "cab" are anagram strings, as every character 'a,' 'b,' and 'c' occur only one time in both the strings. A user will input two strings, and our algorithm counts how many times each character ('a' to 'z') appear in both the strings and then compare their corresponding counts. The frequency of an alphabet in a string is how many times that alphabet appears in the string. For example, the frequency of 'm' in the string "programming" is '2' as it is present two times in "programming."

C anagram program

#include <stdio.h>
int check_anagram(char [], char []);
int main()
   char a[100], b[100];
   int flag;
   printf("Enter first string\n");
   printf("Enter second string\n");
   flag = check_anagram(a, b);
   if (flag == 1)
      printf("%s and %s are anagrams.\n", a, b);
      printf("%s and %s are not anagrams.\n", a, b);
   return 0;
int check_anagram(char a[], char b[])
   int first[26] = {0}, second[26] = {0}, c = 0;
   // Calculating frequency of characters in first string
   while (a[c] != '\0')
   c = 0;
   while (b[c] != '\0')
   // Comparing frequency of characters
   for (c = 0; c < 26; c++)
      if (first[c] != second[c])
         return 0;
   return 1;

Download Anagram program.

Output of C anagram program:
C anagram program output