Hello everyone..
I'm having a hard time to complete this code.
Can anyone help me, because I didn't know how to solve for the percentage.
Thank you
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
void main()
{
char name[50],name2[50];
char *ptr;
char **nameptr = NULL;
int votes;
int max = 0;
int *votes_received = NULL;
float *percent_of_total_votes = NULL;
int offset = 0; //for name_ptr and vote_received
int winner = 0; //check the winner (array element in vote_received)
int i; //for loop
int total = 0; //total votes
while (strcmp(name2, "habis") != 0)
{
printf("Enter name of candidate (habis to exit):");
scanf("%s",&name);
for (i=0;i<=strlen(name);i++)
name2[i] = tolower(name[i]);
if (strcmp(name2, "habis") != 0)
{
printf("Enter %s's votes:",name);
scanf("%d",&votes);
if (nameptr == NULL)
{
nameptr = (char**) malloc(sizeof(char**));
votes_received = (int*) malloc(sizeof(int));
if (nameptr == NULL)
{
printf("Not enough memory 1.\n");
exit(EXIT_FAILURE);
}
}
else
{
nameptr = (char**) realloc(nameptr, (offset + 1) * sizeof(char**));
votes_received = (int*) realloc(votes_received, (offset + 1) * sizeof(int));
if (nameptr == NULL)
{
printf("Not enough memory 2.\n");
exit(EXIT_FAILURE);
}
}
ptr = (char*) malloc(strlen(name));
strcpy(ptr, name);
nameptr[offset] = ptr;
votes_received[offset] = votes;
offset++;
}
} //close while loop
for(i=0;i<offset;i++)
{
total = total + votes_received[i];
percent_of_total_votes[i] = (float)(votes_received[i]/100)*total;
}
printf("\n");
printf("Candidate\tVotes\tPercent\n");
for(i=0;i<offset;i++)
{
printf("%s\t\t",nameptr[i]);
printf("%d\t",votes_received[i]);
printf("%.2f\n",percent_of_total_votes[i]);
if (votes_received[i] > max)
{
max = votes_received[i];
winner = i;
}
}
printf("\nTotal votes : %d\n",total);
printf("The winner is : %s\n\n",nameptr[winner]);
}
Bookmarks