codescracker
c++

C++ Program to Check Strings are Anagram or Not



« Previous Program Next Program »


In this article, you will learn and get code to check whether the given two string by user are anagram or not using C++ programming. But before going through the program, let's first understand, what anagram means.

What are Anagram Strings ?

Two strings will be anagram to each other if and only if they contains the same number of characters.

Note - Order of the characters doesn't matter.

If two strings are anagram, then one string can be rearranged to form the other one. For Example:

Now let's move on to the program.

Check for Anagram String in C++

To check whether the two strings are anagram or not in C++ programming, you have to ask from user to enter the two string to start checking for anagram and display the result on the screen (whether the string is anagram or not) as shown here in the following program.

// Check Strings are Anagram are Not in C++
// ----codescracker.com----

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char str1[20], str2[20];
    int len1, len2, i, j, found=0, not_found=0;
    cout<<"Enter the First String: ";
    cin>>str1;
    cout<<"Enter the Second String: ";
    cin>>str2;
    len1 = strlen(str1);
    len2 = strlen(str2);
    if(len1 == len2)
    {
        for(i=0; i<len1; i++)
        {
            found = 0;
            for(j=0; j<len1; j++)
            {
                if(str1[i] == str2[j])
                {
                    found = 1;
                    break;
                }
            }
            if(found == 0)
            {
                not_found = 1;
                break;
            }
        }
        if(not_found == 1)
            cout<<"\nStrings are not Anagram";
        else
            cout<<"\nStrings are Anagram";
    }
    else
        cout<<"\nCharacter count Mismatched!";
    cout<<endl;
    return 0;
}

This program was build and run under Code::Blocks IDE. Here is its sample run:

c++ anagram program

Now supply any two string say creative and reactive and press ENTER key to see the following output:

anagram program c++

Here, fist we have to check the length of both the string, if the length will be equal then process further. Otherwise print the message for unequal length like Character count Mismatched!. Since two strings to be anagram, their length must have to be same.

Now here compares the first character of first string to all the character of second string one by one. Then compares the second character of first string to all the character of second string. Again compares the third character of first string to all the character of second string, and so on.

While comparing, if any of the character of the first string gets matched to the character of second string, then initialize 1 to a variable say found, and exit the loop. And if there will no match found for any character, then 1 will not initialize to the found. So, found will be equal to 0 (its previous or initial value), Therefore after exiting the inner for loop and checking for the condition if(found==0), evaulates to be true and 1 gets initialized to not_found and exit the outer loop. Therefore after exiting or completing the outer loop, we have to check whether not_found will be equal to 1 or 0. If not_found will be equal to 1, then strings are not anagram, otherwise strings are anagram.

Dry Run of above Program

For example, let's suppose user enters two strings as creative and reactive, then dry run of above program with this input goes like:

  1. The string reactive initialized to str1 and creative initialized to creative in a way that:
    • str1[0]=r
    • str1[1]=e
    • str1[2]=a
    • str1[3]=c
    • str1[4]=t
    • str1[5]=i
    • str1[6]=v
    • str1[7]=e
    • str2[0]=c
    • str2[1]=r
    • str2[2]=e
    • str2[3]=a
    • str2[4]=t
    • str2[5]=i
    • str2[6]=v
    • str2[7]=e
  2. Because the length both the strings is 7. Therefore 7 gets initialized to len1 and len2
  3. Since lengths are equal, therefore the condition of if block evaluates to be true, therefore program flow goes inside its block
  4. Using for loop, 0 gets initialized to i and checks the condition. The condition evaluates to be true, therefore program flow goes inside the loop
  5. 0 gets initialized to found
  6. Now using for loop, 0 gets initialized to j and checks for the condition whether it is less than the value of len1 or not
  7. Condition evaluates to be true, program flow goes inside this loop's body
  8. Evaluates the condition str1[i]==str2[j]. Because the value of i and j is 0, therefore str1[0]==str2[0] or r==c
  9. Condition evaluates to be false, therefore program flow goes to the updation part of this body's first parent loop and increments the value of j
  10. Now j=2
  11. Compares str1[i]==str2[j] or str1[0]==str2[1] or r==r
  12. Condition evaluates to be true
  13. 1 gets initialized to found and using break keyword, program flow skip all the next execution of this for loop.
  14. After exiting from this loop, checks whether the value of found is 0 or not, if it is 0 then the the character at current index of first string does not matched to any character of the second string, therefore 1 gets initialized to not_found
  15. After this if statement, another if block is created to check whether the value of not_found is equal to 1 or not, condition evaluates to be true, then print the string as not anagram, otherwise print it as anagram.
  16. If found holds its value as 1, therefore program flow goes to updation of outer for loop
  17. In this way, now i=1, found=0, j=0
  18. Compares str1[i]==str2[j] or str1[1]==str2[0] or e==c
  19. Condition evaluates to be false, therefore again compares str1[i]==str2[j] or str1[1]==str2[1] or e==r
  20. Condition again evaluates to be false, therefore again compares str1[i]==str2[j] or str1[1]==str2[2] or e==e
  21. This time condition evaluates to be true, therefore found=1 and using break keyword program flow exit from inner for loop
  22. And start from the step no.14 with new value of i
  23. Continue the execution until the value of i becomes equal to the value of len1

Same Program in Other Languages


« Previous Program Next Program »