Saturday 19 March 2016

Anagrams


Write a program to find whether the 2 given strings are anagrams or not. Anagrams are words or phrases made by mixing up the letters of other words or phrases,

Input and Output Format: 
Input consists of 2 string. Assume that all characters in the string are lowercase letters or spaces and the maximum length of the string is 100.
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.

Sample Input and Output 1: 
Enter the first string
anitha
Enter the second string
amphisoft
anitha and amphisoft are not anagrams

Sample Input and Output 2: 
Enter the first string
the eyes
Enter the second string
they see the eyes and they see are anagrams

Code:
  #include<stdio.h>
#include<string.h>
int main(){
  char s1[200],s2[200];
  int first[26]={0},second[26]={0},c=0,i,flag=0;
    //int l,l1;
  printf("Enter the first string\n");
  gets(s1);
  printf("Enter the second string\n");
  gets(s2);
  
    while(s1[c]!='\0')
    {
      first[s1[c]-'a']++;
      c++;
    }
    c=0;
    while(s2[c]!='\0')
    {
      second[s2[c]-'a']++;
      c++;
    }
    for(i=0;i<26;i++){
      if(first[i]!=second[i])
        flag=1;
    }
      
  if(flag==0)
    printf("%s and %s are anagrams",s1,s2);
  else
    printf("%s and %s are not anagrams",s1,s2);
  
  return 0;
}

2 comments:

  1. The program runs for some time and then terminates.Validation takes ages and ultimately get's stuck.Could u help me with this program .

    ReplyDelete
  2. can u please explain me how that while case works !!?? thnak you :)

    ReplyDelete