- C++ Programming Examples
- C++ Programming Examples
- C++: Hello World
- C++: Get Input
- C++: Print Integer
- C++: Add two numbers
- C++: Add, Sub, Multiply, Div
- C++: Add Digits
- C++: Find Average and Percentage
- C++: Find Arithmetic Mean
- C++: Sum of n Natural Numbers
- C++: Sum of n Numbers
- C++: Square's Area and Perimeter
- C++: Rectangle's Area and Perimeter
- C++: Triangle's Area and Perimeter
- C++: Area and Circumference
- C++: Find Simple Interest
- C++: Fahrenheit to Celsius
- C++: Celsius to Fahrenheit
- C++: Print Prime Numbers
- C++: Reverse a Number
- C++: Swap Two Numbers
- C++: Print Multiplication Table
- C++: Find Factorial of a Number
- C++: Find Factors of a Number
- C++: Find HCF and LCM
- C++: Create a Calculator
- C++: Count Digits in a Number
- C++: First and Last Digit Sum
- C++: Product of Number Digits
- C++: Sum of Squares of Digits
- C++: Interchange Digits of Number
- C++ if-else Programs
- C++: Check Even or Odd
- C++: Check Prime or Not
- C++: Check Alphabet or Not
- C++: Check Vowel or Not
- C++: Check Leap Year or Not
- C++: Check Reverse equals Original
- C++: Check Perfect Number
- C++: Check Palindrome or Not
- C++: Check Armstrong or Not
- C++: Divisibility Test
- C++: Find Labor Wage
- C++: Find Discounted Price
- C++: Find Shipping Charge
- C++: Find Telephone Bills
- C++: Calculate Student Grade
- C++: Largest of Two Numbers
- C++: Largest of Three Numbers
- C++ Number Conversion
- C++: Decimal to Binary
- C++: Decimal to Octal
- C++: Decimal to Hexadecimal
- C++: Binary to Decimal
- C++: Binary to Octal
- C++: Binary to Hexadecimal
- C++: Octal to Decimal
- C++: Octal to Binary
- C++: Octal to Hexadecimal
- C++: Hexadecimal to Decimal
- C++: Hexadecimal to Binary
- C++: Hexadecimal to Octal
- C++ Pattern Programs
- C++: Pattern Programs
- C++: Print Diamond Pattern
- C++: Print Floyd's Triangle
- C++: Print Pascal's Triangle
- C++ Array Programs
- C++: 1D Array Program
- C++: Linear Search
- C++: Binary Search
- C++: Largest Element in an Array
- C++: Smallest Element in an Array
- C++: Find Second Largest Element
- C++: Find Second Smallest Element
- C++: Sum of All Elements
- C++: Multiply All Elements
- C++: Element in Even Position
- C++: Element in Odd Position
- C++: Print Even Numbers in Array
- C++: Print Odd Numbers in Array
- C++: Count Even or Odd Numbers
- C++: Sum of Even or Odd Numbers
- C++: Count Positive, Negative, Zero
- C++: Reverse an Array
- C++: Insert an Element
- C++: Delete an Element
- C++: Merge two Arrays
- C++: Bubble Sort
- C++: Selection Sort
- C++: Insertion Sort
- C++: Common Elements
- C++: 2D Array Programs
- C++: Add Two Matrices
- C++: Subtract Two Matrices
- C++: Transpose Matrix
- C++: Multiply Two Matrices
- C++: 3D Array Programs
- C++ String Programs
- C++: Print String
- C++: Find String Length
- C++: Compare Two Strings
- C++: Copy String
- C++: String Concatenation
- C++: Reverse a String
- C++: Delete Vowels from a String
- C++: Delete a Word from a String
- C++: Count Characters in a String
- C++: Count Words in a String
- C++: Frequency of Words
- C++: Remove Spaces from Strings
- C++: Sort a String
- C++: Uppercase to Lowercase
- C++: Lowercase to Uppercase
- C++: Swap Two Strings
- C++: Check the Anagram or Not
- C++: Capitalize All Words in a String
- C++: Get Numbers from a String
- C++ File Programs
- C++: Read a File
- C++: Write Content to a File
- C++: Append Data to a File
- C++: Read and Display File
- C++: Copy a File
- C++: Merge Two Files
- Count Characters in a File
- C++: Capitalize Every Word
- C++: List Files in Directory
- C++: Delete a File
- C++: Encrypt and Decrypt a File
- C++ Misc Programs
- C++: Print ASCII Value
- C++: Add Binary Numbers
- C++: Generate Random Numbers
- C++: Print a Smiling Face
- C++: Days into Years and Months
- C++: Add Two Numbers using Pointer
- C++: Print Fibonacci Series
- C++: Generate Armstrong Numbers
- C++: Find nCr and nPr
- C++: Get IP Address
- C++: Print Date and Time
- C++: Shutdown and Restart Computer
- C++ Programming Tutorial
- C++ Tutorial
C++ Program to Check Whether Strings are Anagrams or Not
In this article, you will learn and get code to check whether the given two strings by the user are anagrams or not using C++ programming. But before going through the program, let's first understand what an anagram means.
What are anagram strings?
Two strings will be anagrams of each other if and only if they contain the same number of characters.
Note: The order of the characters doesn't matter.
If two strings are anagrams, then one string can be rearranged to form the other one. For Example:
- abc and cba are anagrams.
- creative and reactive are also anagrams.
Now let's move on to the program.
In C++, check for anagram strings
To check whether the two strings are anagrams or not in C++ programming, you have to ask the user to enter the two strings to start checking for anagrams and display the result on the screen (whether the string is an anagram or not) as shown here in the following program.
#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 built and runs under the Code::Blocks IDE. Here is its sample run:
Now supply any two strings, say creative and reactive, and press the ENTER key to see the following output:
First, we must compare the lengths of both strings; if they are equal, we can proceed.Otherwise, print the message with an unequal length, like "Character count mismatched!" Because two strings must be anagrams, they must be the same length.
Now, one by one, compare the first character of the first string to all of the characters of the second string. Then it compares the second character of the first string to all the characters of the second string. Again, compare the third character of the first string to all the characters of the second string, and so on.
While comparing, if any of the characters of the first string get matched to the characters of the second string, then initialize 1 to a variable named "found" and exit the loop. And if there is no match found for any character, then 1 will not initialize to it. 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), it evaluates to be true and 1 gets initialized to not_found, and we 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 is equal to 1, then strings are not anagrams; otherwise, strings are anagrams.
Above Program Dry Run
For example, if the user enters two strings as reactive and creative, the dry run of the above program with this input goes like this:
- The reactive string is set to str1, and the creative string is set to str2 in such 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
- because the length of both strings is 7. Therefore, 7 gets initialized to len1 and len2.
- Because the lengths are equal, the condition of the if block evaluates to true, and program flow continues inside its block.
- Using the for loop, 0 gets initialized to i and checks the condition. The condition evaluates to be true, therefore program flow goes inside the loop.
- 0 gets initialized to found
- Now, using the for loop, 0 is initialized to j and checked to see if it is less than the value of len1.
- condition evaluates to be true, program flow goes inside this loop's body.
- Evaluates the condition str1[i]==str2[j]. Because i and j are both zero, str1[0]==str2[0] or r==c.
- 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.
- Now j=2
- Compares str1[i]==str2[j] or str1[0]==str2[1] or r==r
- the condition evaluates to true
- 1 gets initialized to found, and using the break keyword, program flow skips all the next executions of this for loop.
- After exiting this loop, the value of found is checked to see if it is 0; if it is 0 then the character at the current index of the first string does not match any character of the second string, so 1 is initialized to not_found.
- After this if statement, another if block is created to check whether the value of not_found is equal to 1 or not. If the condition evaluates to true, then print the string as an anagram; otherwise, print it as an anagram.
- If it is found, it retains its value of 1, and the program flow proceeds to updating the outer for loop.
- In this way, now i = 1, found = 0, and j = 0.
- Compares str1[i]==str2[j], str1[1]==str2[0], or e==c.
- Because the condition evaluates to false, compare str1[i] == str2[j] or str1[1] == str2[1] or e == r once more.
- Condition evaluates to false again, so compares str1[i]==str2[j] or str1[1]==str2[2] or e==e.
- This time condition evaluates to true, so found=1 and the program flow exits the inner for loop using the break keyword.
- And begin again at step 14 with the new value of i.
- Continue the execution until the value of i becomes equal to the value of len1.
The same program in different languages
« Previous Program Next Program »