Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

There are 7 candidates in an election. Each voter is allowed one vote for the ca

ID: 3561342 • Letter: T

Question

There are 7 candidates in an election. Each voter is allowed one vote for the candidate of his /her choice. The vote is recorded as a number from 1-7 for each candidate respectively. There are 365 voters in all. Any vote which is not a number 1-7 is invalid and counted as a spoilt vote. You have been commissioned to write a program to automate the computation of the winner of the election. For your task you will be provided with one input file elections.txt.

1. Create a struct to represent candidates. Your struct should have 2 fields: name which stores the candidate

Explanation / Answer

//C version of the previous code

#include<stdio.h>
#include<string.h>
#define true 1
#define false 0

typedef int bool;

struct Candidate{
char name[20];
int votes;
}electionCandidates[7];

int spoiltVotes;

void initialize(FILE* fp){
int i;
char name[20];
for(i=0;i<7;i++){
fgets(name,20,(FILE*)fp);
strcpy(electionCandidates[i].name,name);
electionCandidates[i].votes=0;
}
}

void processVotes(FILE* fp){
int i;
while(!feof(fp)){
fscanf(fp,"%d",&i);
if(i >= 1 && i <= 7)electionCandidates[i-1].votes++;
else spoiltVotes++;
}
}

void setWinner(bool* winners, int n){
int i;
for(i=0;i<7;i++){
if(i == n) winners[i]=true;
else winners[i]=false;
}
}

void printResults(){
int max=electionCandidates[0].votes;
int pos=0;
int i;
bool winners[7]={true,false,false,false,false,false,false};
bool tie=false;
int tieCount=0;
for(i=1;i<7;i++){
if(electionCandidates[i].votes > max){
max = electionCandidates[i].votes;
setWinner(winners,i);
pos = i;
tie = false;
tieCount=0;
}
else if(electionCandidates[i].votes == max){
tie = true;
winners[i]=true;
tieCount++;
pos = i;
}
}
if(tie == false){
printf("Winning Candidate is %s",electionCandidates[pos].name);
printf(" who got a total of %d votes ",electionCandidates[pos].votes);
printf("%d votes were spoilt ",spoiltVotes);
}
else{
printf("There was a tie between the candidates ");
for(i=0;i<7;i++){
if(winners[i] == true){
printf("%s",electionCandidates[i].name);
if(tieCount > 0){
printf(" and ");
tieCount--;
}
}
}
printf(" who got a total of %d votes each ",electionCandidates[pos].votes);
printf("%d votes were spoilt ",spoiltVotes);
}
}

int main()
{
FILE* fp;
fp = fopen("elections.txt","r");
initialize(fp);
int spoiltVotes = 0;
processVotes(fp);
printResults();
return 0;
}