Anagram Program in C++

We will learn to check whether the two strings are anagram or not in C++ language. The frequency of the two strings are same but the order of the characters are not same then the two strings are anagram strings.

Frequency of a string is nothing but a character occurs how many times in a string. For example consider a string Codingdiksha. Character i occurs 2 times in this string. Frequency of i is 2.

If the frequency of all characters are same then the strings are anagram strings otherwise two strings are not anagram.

Anagram Program in C++

Anagram Program in C++

#include <iostream>
using namespace std;
int main()
{
    //Initializing variables.
    char str1[100],str2[100];
    int first[26]={0}, second[26]={0}, c=0, flag=0;
    
    //Accepting inputs.
    cout<<"Enter First String: ";
    gets(str1);
    cout<<"Enter Second String: ";
    gets(str2);
    
    //Calculating frequencies of characters in first string.
    while(str1[c] != '\0')
    {
        first[str1[c]-'a']++;
        c++;
    }
     
    c=0;
    //Calculating frequencies of characters in second string. 
    while(str2[c] != '\0')
    {
        second[str2[c]-'a']++;
        c++;
    }
    //Checking if frequencies of both the strings are same or not.
    for(c=0;c<26;c++)
    {
        if(first[c] != second[c])
            flag=1;
    }
    //Priting result.
    if(flag == 0)
    {
        cout<<"Strings are anagram.";
    }
    else
    {
        cout<<"Strings are not anagram.";
    }
    return 0;
  
}

The frequency of the two strings are counted using while loop. For loop iterates to check whether the frequency of two strings are same or not. If the frequency is same then set flag=1 and else set=0.

Read Also : Find Transpose of a Matrix in C++

Output

Enter First String: listen
Enter Second String: silent
Strings are anagram.

Final Words

I hope this article helps you to Anagram Program in C++ Program. If you face any issues please let me know via the comment section. Share this article with other C++ program developers via social networks.

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment