Index
Starting
Here We are going to create an voting system in C Language which allows user to vote for candidate and view the results. It tracks the votes for each candidate and displays the winner based on the number of votes.
Voting System Formula
The Program tracks the votes for each candidate using a simple increment operation wherever a vote is cast:
votes [i] += 1
where “i” is the index of candidate being voted for:
Source Codes
Complete Source Code of voting System,
#include <stdio.h> #include <string.h> #define MAX_CANDIDATES 3 #define MAX_VOTERS 100 typedef struct { char name[50]; int votes; } Candidate; void initializeCandidates(Candidate candidates[]) { strcpy(candidates[0].name, "Alice"); candidates[0].votes = 0; strcpy(candidates[1].name, "Bob"); candidates[1].votes = 0; strcpy(candidates[2].name, "Charlie"); candidates[2].votes = 0; } void displayCandidates(Candidate candidates[]) { printf("Candidates:\n"); for (int i = 0; i < MAX_CANDIDATES; i++) { printf("%d. %s\n", i + 1, candidates[i].name); } } void vote(Candidate candidates[]) { int choice; printf("Enter the number of the candidate you want to vote for: "); scanf("%d", &choice); if (choice >= 1 && choice <= MAX_CANDIDATES) { candidates[choice - 1].votes++; printf("You voted for %s.\n", candidates[choice - 1].name); } else { printf("Invalid candidate number.\n"); } } void displayResults(Candidate candidates[]) { printf("\nElection Results:\n"); for (int i = 0; i < MAX_CANDIDATES; i++) { printf("%s: %d votes\n", candidates[i].name, candidates[i].votes); } } void displayWinner(Candidate candidates[]) { int maxVotes = -1; int winnerIndex = -1; for (int i = 0; i < MAX_CANDIDATES; i++) { if (candidates[i].votes > maxVotes) { maxVotes = candidates[i].votes; winnerIndex = i; } } printf("\nThe winner is %s with %d votes!\n", candidates[winnerIndex].name, candidates[winnerIndex].votes); } int main() { Candidate candidates[MAX_CANDIDATES]; int voterCount = 0; int choice; initializeCandidates(candidates); while (1) { printf("\nVoting System Menu:\n"); printf("1. Display Candidates\n"); printf("2. Vote\n"); printf("3. Display Results\n"); printf("4. Display Winner\n"); printf("5. Exit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch (choice) { case 1: displayCandidates(candidates); break; case 2: if (voterCount < MAX_VOTERS) { vote(candidates); voterCount++; } else { printf("Maximum number of voters reached.\n"); } break; case 3: displayResults(candidates); break; case 4: displayWinner(candidates); break; case 5: printf("Exiting program.\n"); return 0; default: printf("Invalid choice. Please try again.\n"); } } return 0; }