In: Computer Science
Program must be in C
Write a program that allows the user to enter the last names of five candidates in a local election and the number of votes received by each candidate in two different arrays.
The program should then output each candidate’s name, the number of votes received, and the percentage of the total votes received by the candidate.
Your program should also output the winner of the election.
Example (Letters and numbers with underscore indicate an input):
Enter candidate's name and the votes received by the candidate. Johnson 5000 Miller 4000 Duffy 6000 Robinson 2500 Asthony 1800 Candidate Votes Received % of Total Votes --------- -------------- ---------------- Johnson 5000 25.91 Miller 4000 20.73 Duffy 6000 31.09 Robinson 2500 12.95 Asthony 1800 9.33 Total Votes: 19300 The Winner of the Election is: Duffy
Thanks for the question, here is the C program, with output screenshot
================================================================================
#include <stdio.h>
int main(){
char candidates[5][20]; // to store candidate names
int votes[5]={0,0,0,0,0}; // to store votes for each candidate
int totalVotes =0; // total votes of all 5 candidates
int winnerIndex =0; // index of the candidate with highest vote
int i ;
printf("Enter candidate\'s name and the votes received by the candidate.\n");
for(i=0; i<5; i++ ){
scanf("%s %d",&candidates[i],&votes[i]);
totalVotes +=votes[i]; // add the count in the accumulator
if(votes[winnerIndex]<votes[i]){
winnerIndex = i; // run time update the winner index
}
}
// display the results
printf("%20s %20s %20s\n","Candidate","Votes Received","% of Total Votes");
printf("%20s %20s %20s\n","---------","--------------","----------------");
for(i=0; i<5; i++ ){
printf("%20s %20d %20.2f\n",candidates[i],votes[i],votes[i]*100.0/totalVotes);
}
printf("\nTotal Votes: %d",totalVotes);
printf("\nThe Winner of the Election is: %s",candidates[winnerIndex]);
}