Anagram program in C with explanation

In this tutorial, you will learn how to write a program in the C to check the given strings are Anagram or not.

The Complete logic behind it is :

  • To check given strings are anagram or not for that purpose we have to match each character of the string.
  • And also we have to count the occurrence of each characters from both the strings.
  • To implement it first we will arrange both strings in the same order.
  • And then compare each character of both string position wise.
  • If all positions have the same character in both strings then it means strings are anagram otherwise it is not an anagram.

Now before moving on writing the program first you should also know

What is Anagram in String?

Two strings can be called Anagram if the same character with the same occurrence, present in both string. In this case position of characters not matters.

For eg:  “quescol” and “colsque” both strings are anagram. As you can see here, both the string have same character with same time of occurrence at different position and it is an anagram.

But if we take another example like “love” and “like”. In the both string only two character ‘l’ and ‘e’ are common and rest are not. So this two strings are not an anagram.

How our program will behave?

This Program will take two String as an input. And after the comparison it will return output as Strings are anagram or not.

If the string is anagram then it will return “Given Strings are anagram” as an output.

And if Strings are not anagram then it will return “Strings are not anagram”.

Anagram Program in C

#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
    char str1[100], str2[100], ch,temp;
    int i, len1,len2, j;
    printf("Please Enter first String :  ");
    fgets(str1, 100, stdin);
    printf("Please Enter second String :  ");
    fgets(str2, 100, stdin);
    len1 = strlen(str1);
    len2 = strlen(str2);
    if(len1 != len2) {
        printf("given strings are not anagram");
        return 0;
    }
    for (i = 0; i < len1-1; i++) {
        for (j = i+1; j < len1; j++) {
            if (str1[i] > str1[j]) {
                temp  = str1[i];
                str1[i] = str1[j];
                str1[j] = temp;
            }
            if (str2[i] > str2[j]) {
                temp  = str2[i];
                str2[i] = str2[j];
                str2[j] = temp;
            }
        }
    }
    for(i = 0; i<len1; i++) {
        if(str1[i] != str2[i]) {
            printf("Strings are not anagram");
            return 0;
        }
    }
    printf("Given Strings are anagram");
    getch();
}

Output 1:

Please Enter first String :  Quescol
Please Enter second String :  Web
Strings are not anagram

Output 2:

Please Enter first String :  quescol
Please Enter second String :  colques
Given Strings are anagram

Explanation of the Anagram C program

  • Above program is to check given two strings are anagram or not.
  • All logic is written in the main() method.
  • We have 4 char variables str1, str2, ch and temp. str1 and str2 is array of character.
  • We have also integer variable i, len1, len2 and j.
  • Here the logic is very simple. We are taking here two strings as an input and then arranging it in ascending order .
  • Now then we are comparing both strings character, positions wise.
  • As string are a combination of characters. And each character are stored at array index.
  • It both strings are same then it will return output as “Strings are anagram”.
  • And if strings are not equal then it will return “Given Strings are not anagram”.

Anagram Program in C Using Function

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

#define RANGE 256 // Number of possible ASCII characters

bool checkAnagram(char *str1, char *str2) {
    int count[RANGE] = {0};
    int i;
    
    for (i = 0; str1[i] && str2[i]; i++) {
        count[(int)str1[i]]++;
        count[(int)str2[i]]--;
    }

    if (str1[i] || str2[i])
        return false;

    for (i = 0; i < RANGE; i++)
        if (count[i])
            return false;  

    return true;  
}

int main() {
    char str1[100], str2[100];
    printf("Please Enter first String: ");
    scanf("%s", str1);
    printf("Please Enter second string: ");
    scanf("%s", str2);

    if (checkAnagram(str1, str2))
        printf("Given Strings are anagram.\n");
    else
        printf("Given Strings are not anagram.\n");

    return 0;
}

Output

Please Enter first String: quescol
Please Enter second string: colques
Given Strings are anagram.

Explanation of the Anagram C program

  • It includes standard input-output header stdio.h for basic I/O operations, string.h for string operations (though it’s not used in the given code), and stdbool.h for using true or false values.
  • RANGE 256 defines the total number of ASCII characters to create an array that counts the frequency of each character.
  • Function checkAnagram: This boolean function compares two strings to check if they are anagrams. It does so by:
  • Initializing a count array to keep track of character frequencies, set to zero for all.
    • Incrementing the count for each character in str1 and decrementing for str2 in a loop. If the strings are anagrams, all counts should return to zero.
    • Checking if both strings are of the same length. If not, it returns false immediately.
    • Finally, inspecting the count array for any non-zero values. If found, it means the strings are not anagrams, returning false. If all are zero, the function returns true.
  • Main Function:
    • Declares two strings str1 and str2 with a buffer size of 100 characters each.
    • Prompts the user to enter the strings.
    • Calls checkAnagram with the user-provided strings. Depending on the return value, it prints whether the strings are anagrams or not.

This was the all logic behind checking the given two strings are anagram or not.

I would recommend go through this program once again if any doubt.

It will help you to understand it.

Leave a Comment