Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cs50.h>
- #include <stdio.h>
- #include <string.h>
- #define MAX 9 // max number of candidates
- typedef struct // candidates have name and vote count
- {
- string name;
- int votes;
- }
- candidate;
- candidate candidates[MAX]; // array of candidates
- int candidate_count; // number of candidates
- bool vote(string name); // function prototypes
- void print_winner(void);
- int main(int argc, string argv[])
- {
- if (argc < 2) // check for invalid usage
- {
- printf("Usage: plurality [candidate ...]\n");
- return 1;
- }
- candidate_count = argc - 1; // populate array of candidates
- 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++) // loop over all voters
- {
- string name = get_string("Vote: ");
- if (!vote(name)) // check if vote() returns FALSE, if so...
- {
- printf("Invalid vote.\n");
- }
- }
- print_winner(); // display winner of election
- }
- bool vote(string name) // update vote totals given a new vote
- {
- for (int i = 0; i < candidate_count; i++) // iterate through each of the candidates[] one by one
- {
- if (strcmp(name, candidates[i].name) == 0) // compare the strings "name" and candidate[i].name. IF they match...
- {
- candidates[i].votes++; // add a value of 1 to the candidates votes
- return true; // return TRUE, indicating the vote is valid
- }
- }
- return false; // else return false to where this functionis being called
- }
- void print_winner(void) // print winner of election
- {
- int maxvote = 0; // integer vairable in memory to store the value of the highest amount of votes that will be collected
- for (int i = 0; i < candidate_count; i++) // loop through each of the candidates[]
- {
- if (candidates[i].votes >= maxvote)
- {
- maxvote = candidates[i].votes;
- }
- }
- for (int i = 0; i < candidate_count; i++) // loop through each of the candidates[] (again)
- {
- if (candidates[i].votes == maxvote) // if the "ith" candaidates vote count == the maxvote variable
- {
- printf("%s WINNER: ", candidates[i].name); // print the name of the candidate at this index
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement