Write a program in C with the following: This program should simulate a poll for
ID: 3705595 • Letter: W
Question
Write a program in C with the following:
This program should simulate a poll for Mayor of Center City. There must be 5 candidates: John Cole, Anne Drake, Alex Wood, Mary Lee and Ethan Barn. The simulation must be able to input the number of voters and present the results in terms of percentage for each candidate, in order of votes.
Steps:
- show some information about the program on screen;
- input the number of voters;
- create an array to store the individual votes for each candidate (the size of the array should be the number of voters);
- use the C Library function rand to simulate the votes;
- use the array with the votes to count the votes for each candidate;
- create a second array to store the number of votes per candidate (the size of the array should be the number of candidates); and
- show the results on screen.
For example:
This is a poll simulation for Mayor of Center City.
Candidates:
John Cole
Anne Drake
Alex Wood
Mary Lee
Ethan Barn
Please, enter the number of voters: 10512
In this poll, the statistics are:
--------------------------------------------------------
Rank Candidate Votes Percentage
1st Alex Wood 3312 31.50685%
2nd Mary Lee 2348 22.33638%
3rd John Cole 2129 20.25304%
4th Anne Drake 1968 18.72146%
5th Ethan Barn 755 7.182268%
-------------------------------------------------------
Explanation / Answer
Note: The code is having some problem...I will rectify it..
_______________
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main( )
{
int seedVal = 0;
// t is a 'time_t' type variable
time_t t;
/* Intializes random number generator */
seedVal = (unsigned)time(&t);
srand(seedVal);
char* names[]={"John Cole","Anne Drake","Alex Wood","Mary Lee","Ethan Barn"};
int noOfVotes,num;
int votes[5]={0},i,j;
printf("Please, enter the number of voters: ");
scanf("%d",&noOfVotes);
for(i=0;i<noOfVotes;i++)
{
votes[rand()%(5)]++;
}
//This Logic will Sort the Array of elements in Ascending order
int temp;
char tname[100];
for (i = 0; i < 5; i++)
{
for (j = i + 1; j < 5; j++)
{
if (votes[i] > votes[j])
{
temp = votes[i];
votes[i] = votes[j];
votes[j] = temp;
strcpy(tname,names[i]);
strcpy(names[i],names[j]);
strcpy(names[j],tname);
}
}
}
printf(" In this poll, the statistics are: ");
printf("-------------------------------------------------------- ");
printf("Rank Candidate Votes Percentage ");
for(i=0;i<5;i++)
{
printf("%d %s %d %f ",i+1,names[i],votes[i],(((double)votes[i])/noOfVotes)*100);
}
printf("-------------------------------------------------------- ");
return 0;
}
_______________
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.