C program to find the election winner

In this example, we will create a simple C program that simulates an election. The program allows the user to input the names of candidates and the number of votes they received. After collecting this information, the program determines the winner based on the candidate with the highest number of votes. The result is then displayed, showing the name of the winning candidate and the total number of votes they garnered.

Note: You need to have an understanding of structures in C to understand this program.

Program

#include <stdio.h>

struct Candidate{

    char name[25];

    int no_of_votes;

};

int main()

{

    int winnerCount, index;

    struct Candidate cn[5];

    

    for(int i = 0; i <= 4; i++) {

        

        printf("Enter Candidate name: ");

        scanf("%s", cn[i].name);

        printf("\n");

        printf("Enter no of votes: ");

        scanf("%d", &cn[i].no_of_votes);

        printf("\n");

        

    }

    

    for(int i = 0; i <= 4; i++) {

        if(i != 4) {

            if(cn[i].no_of_votes > cn[i + 1].no_of_votes) {

                winnerCount = cn[i].no_of_votes;

                index = i;

            }

        }

    }

    

    printf("The winner is %s with %d votes", cn[index].name, winnerCount);

    

    return 0;

}

Output:

Enter no of votes: 10000

Enter Candidate name: B

Enter no of votes: 12000

Enter Candidate name: C

Enter no of votes: 7000

Enter Candidate name: D

Enter no of votes: 15000

Enter Candidate name: E

Enter no of votes: 11500

The winner is D with 15000 votes

Explanation

  • The program includes the standard input-output header file (#include <stdio.h>).
  • Next, a structure named Candidate is defined, which has two members – name (an array of characters to store the candidate’s name) and no_of_votes (an integer to store the number of votes the candidate received).
  • int winnerCount, index: Variables to store the maximum number of votes (winnerCount) and the index of the winning candidate (index).
  • struct Candidate cn[5]: An array of structures to store information about 5 candidates.
  • A loop (for loop) is used to input the names and the number of votes for each candidate using the scanf function.
  • Another loop is used to iterate through the candidates and find the one with the maximum votes.
  • The loop compares the number of votes of each candidate with the next one, and if the current candidate has more votes, it updates the winnerCount and index variables.
  • Finally, the program prints the name and the number of votes of the winning candidate using the values stored in the index and winnerCount variables.