An election is contested by 5 candidates. The candidates are numbered 1 to 5 and the voting is done by marking the candidate number on the ballot paper. Write a program to read the ballots and count the votes cast for each candidate using an array variable count.
In case a number is read outside the range of 1 to 5, the ballot should be considered as spoilt ballot and the program should count the number of spoilt ballots.
This is a simple C++ program that simulates an election by reading the ballots and counting the votes cast for each candidate using an array called count
. If a number is entered outside the range of 1 to 5, the ballot is considered spoilt, and the program counts the number of spoilt ballots
.
Tutorial 📺
Code 💻
#include <iostream.h>
#include <conio.h>
#include <ctype.h>
class Election
{
int sb, count[5];
public:
Election() // default construction
{
// Data Members Initialization
sb = 0;
for(int i=0; i<5; i++)
count[i] = 0;
cout << "\t\t\tElection";
cout << "\nPress 1 to VOTE for Candidate 1";
cout << "\nPress 2 to VOTE for Candidate 2";
cout << "\nPress 3 to VOTE for Candidate 3";
cout << "\nPress 4 to VOTE for Candidate 4";
cout << "\nPress 5 to VOTE for Candidate 5" << endl;
}
void castVote()
{
int vote;
cout << "\nPlease cast your vote: ";
cin >> vote;
if (vote >= 1 && vote <= 5)
count[vote-1]++;
else
sb++;
}
void electionResults()
{
clrscr();
cout << "\n\t\t\tElection Results" << endl;
for (int i=0; i<5; i++)
cout << "\nCandidate " << i+1 << " got " << count[i] << " votes.";
cout << "\n\nSpoilt Ballots: " << sb << endl;
}
}; // class Election ends here
void main()
{
clrscr();
char choice;
Election ele; // object of class Election
do
{
ele.castVote();
cout << "Anyone left?(y/n): ";
cin >> choice;
} while(toupper(choice) == 'Y'); // iterate if anyone is left.
ele.electionResults(); // display the Election Results
getch();
}
Explanation 🤔
The above program includes three functions:
- Constructor: In the default constructor, the program initializes an array
count
to keep track of the votes received by each candidate and a variablesb
to count the spoilt ballots. - castVote(): This function is responsible for taking input from voters, verifying if the input is a valid candidate number (between 1 and 5), and updating the vote count for the respective candidate. If the input is outside this range, it is considered a spoilt ballot.
- electionResults(): After all votes have been cast, this function displays the election results, showing the number of votes received by each candidate and the number of spoilt ballots.
In the main()
function, the program starts by creating an instance of the Election
class. It then enters a loop, prompting voters to cast their votes and asking if anyone is left to vote. The loop continues until the user indicates that there are no more voters.
Comments