Find number of votes of winning candidate
Question
Write a program to find a number of votes of winning candidate. Make an election system and count the votes of each candidate.
Logic
- First, get the votes of the people for the candidates.
- A person can vote the candidate based on the candidate id.
- Finally, print the maximum votes acquired by individual candidate.
Algorithm
- Get the votes for five candidates and store the count in the individual array.
- After the voting, Sort the array using bubble sort.
- Print the last element (maximum) of the array.
Program
[code lang=”java”]
import java.util.Scanner;
class Election
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
int no=5;
int i = 0,j,count,nota=0,k;
int arr[]=new int [5];
System.out.println("Candidates id: 1-5");
System.out.println("press 6 for nota");
for(i=0;i<no;i++)
{
System.out.println("person"+(i+1)+"’s vote");
count=s.nextInt();
switch(count)
{ case 1: arr[0]++;
break;
case 2:arr[1]++;
break;
case 3:arr[2]++;
break;
case 4:arr[3]++;
break;
case 5:arr[4]++;
break;
default:
nota++;
}
}
//using bubble sort to find maximum vote
for(i=no;i>0;i–)
{
for(j=0,k=1;k<i;j++,k++)
{
if(arr[j]>arr[k])
{
int swap=arr[j] ;
arr[j]=arr[k];
arr[k]=swap;
}
}
}
System.out.println("candidate wins "+arr[no-1]+ "votes");
}
}
[/code]