This was part of the cs50 assignment. Its a simple program which takes in the name of the candidate as vote and outputs the one which got called the highest time. I tried running it, but it always outputs all the candidates as winners. When I looked into it the candidates[i].votes doesn't increment even though the code is present. I just wanna know why this is occurring.
#define MAX 9
void count(string name);
typedef struct
{
string name;
int votes;
}
candidate;
candidate candidates[MAX];
int candidate_count;
void print_winner(void);
int main(int argc, string argv[])
{
if (argc < 2)
{
printf("Usage: plurality [candidate ...]\n");
return 1;
}
candidate_count = argc - 1;
if (candidate_count > MAX)
{
printf("Maximum number of candidates is %i\n", MAX);
return 2;
}
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i + 1];
candidates[i].votes = 0;
}
int voter_count = get_int("Number of voters: ");
for (int i = 0; i < voter_count; i++)
{
string name = get_string("Vote: ");
count(name);
}
print_winner();
}
void count(string name)
{
for (int i = 0; i < candidate_count; i++)
{
if (name == candidates[i].name)
{
candidates[i].votes = candidates[i].votes + 1;
}
}
}
void print_winner(void)
{
int z = 0;
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes > z)
{
z = candidates[i].votes;
}
}
for (int i = 0; i < candidate_count; i++)
{
if (z == candidates[i].votes)
{
printf("the winner is %s\n",candidates[i].name);
}
}
}