Problem :
How to write a C program for voting using the switch case.
Solution :
We will be considering three candidates for elections. This program will cast and count total votes for a particular candidate. We will be making two functions namely
Give vote : To give vote for a candidate by pressing the number.
Total votes : To count the total no of votes on a particular candidate.
Program :
#include <stdio.h>
#include <conio.h>
#define CANDIDATE_COUNT
#define CANDIDATE1 "Tea"
#define CANDIDATE2 "Spoon"
#define CANDIDATE3 "Plate"
int totalvotes1=0, totalvotes2=0, totalvotes3=0;
void givevote(){
int ch;
printf("\n\n **** Choose your Candidate ****\n\n");
printf("\n 1. %s", CANDIDATE1);
printf("\n 2. %s", CANDIDATE2);
printf("\n 3. %s", CANDIDATE3);
printf("\n4. %s", “None of the above");
printf("\n Select your choice (1 - 4) : “);
scanf("%d",&ch);
switch(ch)
{
case 1: totalvotes1++;
break;
case 2: totalvotes2++;
break;
case 3: totalvotes3++;
break;
default: printf("\n Error: Enter valid choice");
getchar();
}
printf(“\n thanks for voting !!");
}
void totalvotes()
{
printf("\n\n **** Voting Statics ****\n");
printf("\n %s - %d ", CANDIDATE1, totalvotes1);
printf("\n %s - %d ", CANDIDATE2, totalvotes2);
printf("\n %s - %d ", CANDIDATE3, totalvotes3);
}
int main()
{
int i;
int ch;
do{
printf("\n\n **** Welcome to Voting 2022 ****");
printf("\n\n 1. Give the Vote");
printf("\n 2. Find total votes");
printf("\n 0. Exit");
printf("\n Please enter your choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1: givevote();
break;
case 2: totalvotes();
break;
default: printf("\n Error: please enter valid no");
}
}while(ch!=0);
getchar();
return 0;
}
2 Comments
Nice 👍👍👍👍👍👍
ReplyDeleteNice
ReplyDelete