Advertisement
decs4usa

plurality

Jan 24th, 2020
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.70 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 > candidate_count; i++)
  70.     {
  71.         if (strcmp(candidates[i].name, name) == 0)
  72.         {
  73.             return true;
  74.         }
  75.     }
  76.     return false;
  77.  
  78. }
  79.  
  80. // Print the winner (or winners) of the election
  81. void print_winner(void)
  82. {
  83.     int voter_count = 0;
  84.  
  85.     for (int i = 0; i < voter_count; i++)
  86.     {
  87.         if (candidates[i].votes > i)
  88.         {
  89.             printf("%s\n", candidates[i].name);
  90.         }
  91.         return;
  92.     }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement