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 the same number of times (one time here) 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

  1. #include <stdio.h>
  2.  
  3. int check_anagram(char [], char []);
  4.  
  5. int main()
  6. {
  7.   char a[100], b[100];
  8.  
  9.   printf("Enter a string\n");
  10.   gets(a);
  11.  
  12.   printf("Enter a string\n");
  13.   gets(b);
  14.  
  15.   if (check_anagram(a, b) == 1)
  16.     printf("The strings are anagrams.\n");
  17.   else
  18.     printf("The strings aren't anagrams.\n");
  19.  
  20.   return 0;
  21. }
  22.  
  23. int check_anagram(char a[], char b[])
  24. {
  25.   int first[26] = {0}, second[26] = {0}, c=0;
  26.  
  27.   // Calculating frequency of characters of first string
  28.  
  29.   while (a[c] != '\0')
  30.   {
  31.     first[a[c]-'a']++;
  32.     c++;
  33.   }
  34.  
  35.   c = 0;
  36.  
  37.   while (b[c] != '\0')
  38.   {
  39.     second[b[c]-'a']++;
  40.     c++;
  41.   }
  42.  
  43.   // Comparing frequency of characters
  44.  
  45.   for (c = 0; c < 26; c++)
  46.   {
  47.     if (first[c] != second[c])
  48.       return 0;
  49.   }
  50.  
  51.   return 1;
  52. }

Output of C anagram program:
C anagram program output

Download Anagram program.