You are on page 1of 5

Anagram Program in C

What is Anagram?
The two strings are called as Anagram of each other if they contain the
same characters either arranged in sequence or not it is not necessary.

How to check two Strings are Anagram or not?


To check whether the given two strings are Anagram of each other or not the
compiler will ask the user to enter the two strings to check. After the input given by
the user, the program will start executing are check whether the strings are Anagram
or not.

After executing the compiler will display the output. The two strings are Anagram if
and only if characters in that strings are the same sequence is not mandatory.

For Example abcd and dcba, creative and reactive, course and source are Anagram
of each other.
Anagram Algorithm:
1 Step: Declare two Strings.

2 Step: Find out the length of two Strings (Strings are not
anagram if the length of strings is not the same).

3 Step: Even if the lengths are equal the two strings should be
in lowercase because it makes easy to check.

4 Step: Now sort the characters in the strings.For, sorting


convert the strings into a character array.

5 Step: After converting character array must be sorted.

6 Step: In the last step, the Anagram is checked.

There are different ways to check the Anagram program in C


we will see it one by one.

Anagram program in C Using Nested For


Loop:

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char string1[20], string2[20];
int leng, leng1, leng2, a, b, found1=0, not_found1=0;
printf("Enter First String: ");
gets(string1);
printf("Enter Second String: ");
gets(string2);
//length of the first string is calculated
leng1 = strlen(string1);
//length of the first string is calculated
leng2 = strlen(string2);
//compare the length of the two strings to find out if the strings are anagram or
not
if(leng1 == leng2)
{
leng = leng1;
for(a=0; a<leng; a++)
{
found1 = 0;
for(b=0; b<leng; b++)
{
if(string1[a] == string2[b])
{
found1 = 1;
break;
}
}
if(found1 == 0)
{
not_found1 = 1;
break;
}
}
if(not_found1 == 1)
printf("\nThe two entered strings are not Anagram");
else
printf("\nThe two entered strings are Anagram");
}
else
printf("\nsame number of characters must be present in both the strings to be
an Anagram");
getch();
return 0;
}

Output:

You might also like