Anagram Finder in C, How many outputs are adequate? :D

Greetings, fellow coders. I tried looking at different forums but they could not answer my question.

I am currently working on the course LEARN C, I am at the end of the ARRAYS AND STRINGS lesson, and I am working on the ANAGRAM FINDER project.

Here is a description of the prompt.

In this project, we will write a program to determine whether two strings are anagrams or not.

String y is an anagram of string x if y is a rearrangement of string x. This implies that y and x have the same letters with the same amount of each letter. Example: “code” and “deco” are anagrams!

The constraints of this project are: Each string will contain only characters that are from the first four letters of the English alphabet (‘a’, ‘b’, ‘c’, ‘d’) and spaces. All letters are in lowercase.

We will do this by creating two arrays of length four: one for each string that represents the count of each character. These arrays will serve as counters. In each array, the number at position zero corresponds to the count of the letter ‘a’, the number at position one will correspond to the count of the letter ’b’ and this pattern will continue for the remaining letters. We do not count the number of spaces. For example, “a bc d” would be an anagram of “ab cd”.

We will then loop through both strings and update their respective counters.

We will then compare the two counters to see if the two strings are anagrams and if they are, we will print “Anagram!”. If they are not, we will print “Not Anagram!”

Let’s get started!!

The problem that I am stuck on is why the compiler repeats “Anagram” 4 times instead of once?

Below, is a copy of my code:

#include<stdio.h>
#include<string.h>
int main() {
int counter1 = {0, 0, 0, 0};
int counter2 = {0, 0, 0, 0};
char s1 = “dbb cccccaacb cdbababdcdcdab dcdad”;
char s2 = “bbbcc bdddccccad cdbbaaacaccdabdd”;
int flag = 0;
for(int i = 0; i < strlen(s1); i++){
if(s1[i] == ‘a’){
counter1[0]++;
}
else if(s1[i] == ‘b’){
counter1[1]++;
}
else if(s1[i] == ‘c’){
counter1[2]++;
}
else if(s1[i] == ‘d’){
counter1[3]++;
}
else if(s1[i] == ’ ') {
continue;
}
}
for(int i = 0; i < strlen(s2); i++){
if(s2[i] == ‘a’){
counter2[0]++;
}
else if(s2[i] == ‘b’){
counter2[1]++;
}
else if(s2[i] == ‘c’){
counter2[2]++;
}
else if(s2[i] == ‘d’){
counter2[3]++;
}
else if(s1[i] == ’ ') {
continue;
}
}
for(int i = 1; i <=4; i++){
if(counter1[i] = counter2[i]) {
int flag = 1;
}
else {
int flag = 0;
}
if(flag == 0) {
printf(“Anagram!\n”);
}
else {
printf(“Not Anagram!”);
}
}
}

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.