Reputation: 113
I need the for loop to execute 4 times in the program and then to exit at the fourth time and give the total of the results.
It should not count X as a spoilt vote
The three totals and the number of spoilt votes are initialised to 0.
Now a for loop follows, going from 1 to the number of voting stations.
Inside this loop is a while loop. A prompting message appears on the screen, asking the voter for which candidate he or she wants to vote. The choice of the voter is then input.
Inside the while loop is a switch statement to increment the correct total. The default option is used to count the number of spoilt votes.
The while loop is exited when X is entered for the choice.
When the for loop is exited, the three totals and the number of spoilt votes are displayed.
Here is my code
int main()
{
const int NR_VOTING_STATIONS = 4;
int votesForA, votesForB, votesForC, spoiltVotes;
char vote;
// initialise totals
votesForA = 0;
votesForB = 0;
votesForC = 0;
spoiltVotes = 0;
// LOOP of INTEREST START
//loop over the voting stations
for ( int i = 1; i <= NR_VOTING_STATIONS; i++)
{
//loop over voters
while (vote != 'X')
{
cout << "Vote for candidate A, B or C : " << endl;
cin >> vote;
switch(vote)
{
case 'A':
votesForA++;
break;
case 'B':
votesForB++;
break;
case 'C':
votesForC++;
break;
default:
spoiltVotes++;
}
}
}
// LOOP of INTEREST END
//display results
cout << endl << endl;
cout << "Total candidate A : " << votesForA << endl;
cout << "Total candidate B : " << votesForB << endl;
cout << "Total candidate C : " << votesForC << endl;
cout << "Total spoilt votes: " << spoiltVotes << endl;
system("pause");
return 0;
}
Thanks
Upvotes: -1
Views: 831
Reputation: 101
Also, be careful to initialize vote first, or use do { } while() rather than while { }
Upvotes: 1
Reputation: 2950
In the while loop you should check whether the Voters in that polling sttion are still available. Since you are neutral at the input 'X', you should add it as one of the cases in the switch.
Your new while loop should look like:
Voters_Still_Present = 1;
while (Voters_Still_Present)
{
cout << "Vote for candidate A, B or C : " << endl;
cin >> vote;
switch(vote)
{
case 'A':
votesForA++;
break;
case 'B':
votesForB++;
break;
case 'C':
votesForC++;
break;
case 'X':
//do nothing
break;
default:
spoiltVotes++;
}
/* Here, find out if voters are still available in the present station.
If yes, Voters_Still_Present = 1; else Voters_Still_Present = 0;
*/
}
Upvotes: 0
Reputation: 3694
If the question is
It should not count X as a spoilt vote
The answer would be to add a case:
case 'X':
break;
Upvotes: 1
Reputation: 49185
just add in the switch
:
case 'X':
break;
because the while condition will not be executed until the next round.
Upvotes: 1
Reputation: 444
If you need the for loop to execute four times why not just surround it in another for loop?
Upvotes: 0