Directions: You are to write a program that tests whether two words are anagrams
ID: 3639091 • Letter: D
Question
Directions:You are to write a program that tests whether two words are anagrams (permutations of the same letters). Non-alphabetic characters are ignored and lowercase characters are treated as the corresponding upper case character.
As usual, a word is entered letter-by-letter and then the user hits the return key, so the input is terminated by a newline character.
You should use an integer array count of length 26 to keep track of the number of times each alphabetic character appears in the first word. You should #include <ctype.h> which provides the functions isalpha, which tests a character to see that it is alphabetic, and toupper, which converts an alphabetic character to its uppercase form. As for the count array, count[0] should contain the number of ‘A’s in the word, count[1] the number of ‘B’s, … . For an arbitrary uppercase letter ch, count[ch-‘A’] should contain the number of times ch appears in the word.
So, you should write a loop that reads in the first word, character by character, until the newline is encountered. For each alphabetic character, you increment its entry in the count array. Then you write another loop that reads in the second word, character by character, and decrement the count for each such character.
Then the two words are anagrams if and only if the count array contains only zeros
This is what I have so far:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
int count[26], i;
printf(" Enter your first word");
while((ch=getchar()) != ' ')
{
count[toupper(ch)-'A']++;
}
for(i=0 ; i<25 ; i++)
printf("%d", count[i]);
return 0;
}
I am really confused on how to make a loop to read in individual characters then increment the array involved with the character in the same loop.
Explanation / Answer
please rate - thanks
sorry about that--this is actually different then what I posted. I didn't read your entire post.
create an int array of length 26, 1 for each letter. and initialize it to 0, these are the counters, 1 for each letter
starting with the first word
loop through each character. if it is a letter change it to it's number a=0,b=1,...y=24,z=25
add 1 to the corresponding counter.
now do the same for the 2nd word, only now subtract 1 from each letters counter.
when done
loop through all the counters. if they are all 0, the words are anagrams, if all 26 counters are not 0, they are not anagrams
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.