My program given two words should determine whether they are
My program, given two words, should determine whether they are anagrams of each other. However, mine says not an anagram regardless of input. Two of the required tests which are word1 = PAInTer, word2 = repaint, and word1 = ReSCUed, and word2 = SEdUCer. Thanks in advanced! Below is my code:
#include <stdio.h>
 #include <ctype.h>
 #include <string.h>
 #include <stdlib.h>
void anagram_check(char word1[], char word2[]);
 void sort_string(char word[]);
void anagram_check(char word1[], char word2[]) { //this function checks whether two words are anagrams of each other
char temp1[20], temp2[20];
   
 if (strlen(word1) != strlen(word2)) { //if strings are not of equal length, they cannot be anagrams
 printf(\"%s is NOT an anagram of %s\ \", word1, word2);
 exit(0);
 }
   
 for (int i = 0; temp1[i]; i++) { //converting first string to lower case
 temp1[i] = tolower(word1[i]);
 }
 for (int i = 0; temp2[i]; i++) { //converting second string to lower case
 temp2[i] = tolower(word2[i]);
 }
   
 sort_string(temp1); //calls of function to sort string alphabetically so they can easily be compared
 sort_string(temp2);
   
 if (strcmp(temp1, temp2) == 0) { //if string comparison equals 0, it is true that the words are anagrams
 printf(\"%s is an anagram of %s\ \", word1, word2);
 }
   
 else if (strcmp(temp1, temp2) != 0) { //if string comparison does NOT equal 0, it is false that the words are anagrams
 printf(\"%s is NOT an anagram of %s\ \", word1, word2);
 }
 }
void sort_string(char word[]) { //sorts strings alphabetically
 char temp;
 int length;
   
 length = strlen(word); //
   
 for (int i = 0; i < length - 1; i++) { //compares letter to letter and sorts alphabetically, a-z
 for (int j = i + 1; j < length; j++) {
 if (word[i] > word[j]) {
 temp = word[i];
 word[i] = word[j];
 word[j] = temp;
 }
 else {
                word[i] = word[i];
                word[j] = word[j];
 }
 }
 }
 }
   
int main() {
   
 char word1[20], word2[20]; //intializing to max 20 characters
   
 printf(\"Please enter the first word: \");
 scanf(\"%s\", word1);
   
 printf(\"Please enter the second word: \");
 scanf(\"%s\", word2);
   
 anagram_check(word1, word2);
 return 0;
 }
Solution
As far as i understood the approach used is to first check whether the two string are of equal length or not and if yes then it sorts both words in alphabetical order first and then compares the two strings.
The problem i could see with your code is while coverting the words into lower case the for loop limit parameter is temp[i] and there is no limit to i its keep on increasing.You should take the length of words passed as parameter and then loop through till length-1.


