I'm new to C and trying to make an anagram finder, but it doesn't work correctly and I'm not sure where I've gone wrong. It works by counting the number of letters in 2 different strings using 2 seperate integer arrays named counter1
and counter2
. It's then supposed to compare the values in each counter and check for any mismatches, but for some reason it prints both possible outcomes instead of the correct one. Any help appreciated!
#include <stdio.h>
#include <string.h>
int main(){
//Letter counter for each string
int counter1[] = {0, 0, 0, 0};
int counter2[] = {0, 0, 0, 0};
// Strings to be checked
char s1[] = "abcd";
char s2[] = "dcba";
//Checks letter count in string 1
for (int i = 0; i < strlen(s1); i++) {
if (s1[i] == ' ') {
continue; }
else if (s1[i] == 'a') {
counter1[0] += 1; }
else if (s1[i] == 'b') {
counter1[1] += 1; }
else if (s1[i] == 'c') {
counter1[2] += 1; }
else (s1[i] == 'd'); {
counter1[3] += 1; }
}
// Checks letter count in string 2
for (int i = 0; i < strlen(s2); i++) {
if (s2[i] == ' ') {
continue; }
else if (s2[i] == 'a') {
counter2[0] += 1; }
else if (s2[i] == 'b') {
counter2[1] += 1; }
else if (s2[i] == 'c') {
counter2[2] += 1; }
else (s2[i] == 'd'); {
counter2[3] += 1; }
}
//Checks for mismatches in the letter counters
int flag = 0;
int counterLen = sizeof(counter1)/sizeof(int);
for (int i = 0; i < counterLen; i++ ) {
if (counter1[i] != counter2[i]) {
flag++; }
}
//Tells user if it's an anagram or not
if (flag == 0) {
printf("Anagram!"); }
else (flag != 0); {
printf("Not Anagram!"); }
}
This
if (s1[i] == 'c') {
/* irrelevant 1 */ }
else (s1[i] == 'd'); {
/* irrelevant 2 */ }
Does the code from "irrelevant 1" in case s1[i] == 'c'
.
Otherwise it does (s1[i] == 'd');
,
by evaluating a boolean expression and ignoring the result, because it is not used for anything, especially not for an if
, because there is none.
Then it unconditionally does the code in "irrelevant 2". You have that non-pattern at least three times in your shown code.
I assume that the "unconditionally" results one way or another (sorry, not going into details there, because what you seem to actually be asking is what you missed...) in your "it prints both possible outcomes" observation.