C Language: Majority Elections


The third week of Computer Science CS50 (Harvard) training begins and we continue to learn the C language. The first task: the implementation of a voting system where the candidate with the most votes wins, the so-called. plurality system or simply “winner takes all” (plurality.c). The user can choose one from the list of candidates and vote for him. When the votes are counted, the candidate with the most votes is declared the winner of the election.

How to implement such functionality?

  1. In the constant #define MAX n we indicate the maximum number of candidates that can be in the elections;
  2. Let’s create a structure: struct candidate. Each element of this structure will have two fields: the string name (the name of the candidate), and the number of voices (the number of votes that the candidate received).
  3. Let’s create a global array candidates, each element of which belongs to the structure candidate.
  4. Let’s create a global variable candidate_count (the number of candidates in the elections).
  5. Pass the command line arguments to the candidates array.
  6. Ask the user to enter the number of voters.
  7. Ask the user to vote by calling the vote function.
  8. In the print_winner function, we will count the votes and print the name of the winner (or winners) of the election.

As usual, Igroeye works without the cs50.h library, which requires some reworking of the code and the use of pointers. Therefore, the Shtukentsia variant (it is below) looks simpler this time. So, Igroglaz’s solution:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

// Max number of candidates
#define MAX 9

// Candidates have name and vote count
typedef struct
{
    char name[1000];
    int votes;
}
candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates
int candidate_count;

// Function prototypes
bool vote(char *name);
void print_winner(void);

int main(int argc, char *argv[])
{
    int i, j;
    int voter_count;

    // 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 (i = 0; i < candidate_count; i++)
    {
        strcpy(candidates[i].name, argv[i + 1]);
        candidates[i].votes = 0;
    }

    printf("Number of voters: ");
    scanf("%d", &voter_count);
    while (getchar() != '\n') ; // clear buffer

    // Loop over all voters
    for (i = 0; i < voter_count; i++)
    {
        char name[1000]; // local array for user input

        printf("Vote: ");
        // lets the user input candidate name to vote
        for (j = 0; ; j++)
        {
            scanf("%c", &name[j]);
            if (name[j] == '\n')
            {
                name[j] = '\0'; // replace last char from \n to \0
                break;
            }
            // ? maybe add \0
        }

        // Check for invalid vote
        if (!vote(name))
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner();

    getchar();
    getchar();
    return 0;
}

// Update vote totals given a new vote
bool vote(char *name)
{
    int i;

    for (i = 0; i < candidate_count; i++)
    {
        if (strcmp (name, candidates[i].name) == 0)
        {
            candidates[i].votes++;
            return true;
        }
    }

    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    int i;
    int max = 0;

    // find maximum votes
    for (i = 0; i < candidate_count; i++)
    {
        if (max < candidates[i].votes)
            max = candidates[i].votes;
    }

    // print winner(s)
    for (i = 0; i < candidate_count; i++)
    {
        if (max == candidates[i].votes)
            printf("%s\n", candidates[i].name);
    }
    return;
}

Shtukensia’s solution:

The most difficult moment here was to draw the conclusion of the winner. To do this, you need to find the candidate with the highest number of votes. This is where the information about sorting values from the lecture came in handy. One more thing, if the number of votes for several candidates is the same, then the program should show all these candidates.

#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;
    int votes;
}
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];
        candidates[i].votes = 0;
    }

    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();
}

// Update vote totals given a new vote
bool vote(string name)
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (!strcmp(name, candidates[i].name))
        {
            candidates[i].votes += 1;
            return true;
        }
    }
    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    int biggest_vote = 0;
    string winner;

    for (int i = 0; i < candidate_count; i++)
    {
        if (candidates[i].votes > biggest_vote)
        {
            biggest_vote = candidates[i].votes;
            winner = candidates[i].name;
        }
    }

    for (int j = 0; j < candidate_count; j++)
    {
        if (candidates[j].votes == biggest_vote)
        {
            printf("%s\n", candidates[j].name);
        }
    }

    return;

}

Тестируем программу:


This entry was posted in C language (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.