Advertisement
Guest User

Untitled

a guest
Jan 20th, 2020
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.01 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. // Max number of candidates
  6. #define MAX 9
  7.  
  8. // Candidates have name and vote count
  9. typedef struct
  10. {
  11.     string name;
  12.     int votes;
  13. }
  14. candidate;
  15.  
  16. // Array of candidates
  17. candidate candidates[MAX];
  18.  
  19. // Number of candidates
  20. int candidate_count;
  21.  
  22. // Function prototypes
  23. bool vote(string name);
  24. void print_winner(void);
  25.  
  26. int main(int argc, string argv[])
  27. {
  28.     // Check for invalid usage
  29.     if (argc < 2)
  30.     {
  31.         printf("Usage: plurality [candidate ...]\n");
  32.         return 1;
  33.     }
  34.  
  35.     // Populate array of candidates
  36.     candidate_count = argc - 1;
  37.     if (candidate_count > MAX)
  38.     {
  39.         printf("Maximum number of candidates is %i\n", MAX);
  40.         return 2;
  41.     }
  42.     for (int i = 0; i < candidate_count; i++)
  43.     {
  44.         candidates[i].name = argv[i + 1];
  45.         candidates[i].votes = 0;
  46.     }
  47.  
  48.     int voter_count = get_int("Number of voters: ");
  49.  
  50.     // Loop over all voters
  51.     for (int i = 0; i < voter_count; i++)
  52.     {
  53.         string name = get_string("Vote: ");
  54.  
  55.         // Check for invalid vote
  56.         if (!vote(name))
  57.         {
  58.             printf("Invalid vote.\n");
  59.         }
  60.     }
  61.  
  62.     // Display winner of election
  63.     print_winner();
  64. }
  65.  
  66. // Update vote totals given a new vote
  67. bool vote(string name)
  68. {
  69.     for (int i = 0; i < 9; i++)
  70.     {
  71.         if (strcmp(candidates[i].name, name) == 0)
  72.         {
  73.             candidates[i].votes++;
  74.             return true;
  75.         }
  76.  
  77.     }
  78. return false;
  79. }
  80.  
  81. // Print the winner (or winners) of the election
  82. void print_winner(void)
  83. {
  84.     {
  85.         int biggestVote = 0;
  86.         for (int i = 0; i < 9; i++)
  87.         {
  88.             if (candidates[i].votes > biggestVote)
  89.             {
  90.                 biggestVote = candidates[i].votes;
  91.             }
  92.  
  93.         }
  94.         for (int i = 0; i < 9; i++)
  95.         {
  96.             if (candidates[i].votes == biggestVote)
  97.             printf("%s\n", candidates[i].name);
  98.         }
  99.     }
  100.     return;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement