# CS50x Plurality

## From problem set 3

\$ ./plurality Alice Bob Charlie
Number of voters: 4
Vote: Alice
Vote: John
Invalid Vote.
Vote: Charlie
Vote: Alice
Alice
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Max number of candidates
#define MAX 9
// Candidates have name and vote count
typedef struct
{
string name;
}
candidate;
// Array of candidates
candidate candidates[MAX];
// Number of candidates
int candidate_count;
// Function prototypes
bool vote(string name);
void print_winner(void);
int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: plurality [candidate ...]\n");
return 1;
}
// Populate array of candidates
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];
}
int voter_count = get_int("Number of voters: ");// Loop over all voters
for (int i = 0; i < voter_count; i++)
{
string name = get_string("Vote: ");
// Check for invalid vote
if (!vote(name))
{
printf("Invalid vote.\n");
}
}
// Display winner of election
print_winner();
}
bool vote(string name)
{
for (int n = 0; n < candidate_count; n++)
{
if (strcmp(name, candidates[n].name) == 0)
{
return true;
}
}
return false;
}
void print_winner(void)
{
// TODO
int winner = 0;
for (int v = 0; v < candidate_count; v++)
{
{
}
}
for (int w = 0; w < candidate_count; w++)
{
{
printf("%s\n", candidates[w].name);
}
}
}
Results generated by style50 v2.7.4
Looks good!
Results for cs50/problems/2020/x/plurality generated by check50 v3.1.2
:) plurality.c exists
:) plurality compiles
:) vote returns true when given name of first candidate
:) vote returns true when given name of middle candidate
:) vote returns true when given name of last candidate
:) vote returns false when given name of invalid candidate
:) vote produces correct counts when all votes are zero
:) vote produces correct counts after some have already voted
:) vote leaves vote counts unchanged when voting for invalid candidate
:) print_winner identifies Alice as winner of election
:) print_winner identifies Bob as winner of election
:) print_winner identifies Charlie as winner of election
:) print_winner prints multiple winners in case of tie
:) print_winner prints all names when all candidates are tied