In: Computer Science
Write JAVA program that finds 3 students with the best
scores.
The program asks users for scores of 5 students.
The program prints the first, second, third place students and
scores.
You can assume that there is no two students with the same
score.
<EXAMPLE>
enter the score of each student
score of student 1: 50
score of student 2: 70
score of student 3: 30
score of student 4: 90
score of student 5: 40
1st place is student 4 with 90 points.
2nd place is student 2 with 70 points
3rd place is student 1 with 50 points
CODE:
import java.io.*;
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main (String[] args) {
System.out.println("Enter number of
students\n");
Scanner myObj = new
Scanner(System.in); //creating scanner object
int numstud = myObj.nextInt();
//taking number of students from user
int t1=-1;int i1=0;//initializing
t1->top first mark, i1-> index of top first student
int t2=-1;int i2=0;//initializing
t2->top second mark, i2-> index of top second student
int t3=-1;int i3=0;//initializing
t3->top third mark, i3-> index of top third student
for(int i=0;i<numstud;i++)
{
System.out.println("Score of
student"+(i+1));
int mrk = myObj.nextInt();
if(mrk>t1) // if present student
mark greater than top first mark
{
t3=t2;i3=i2; //previous second
holder becomes present third
t2=t1;i2=i1; //previos first
becomes present second
t1=mrk;i1=i+1; //i+1 th student is
top first
}else if(mrk>t2) //if present
student mark less than first but greater than second
{
t3=t2;i3=i2;//previous second
holder becomes present third
t2=mrk;i2=i+1;//i+1 th student is
top second
}else if(mrk>t3) //if present
student mark less than first and second but greater than
third
{
t3=mrk;i3=i+1; //i+1 th student is
top third
}
}
System.out.println("1st place is
student"+i1+ " with "+t1+" points");
System.out.println("2nd place is
student"+i2+ " with "+t2+" points");
System.out.println("3rd place is
student"+i3+ " with "+t3+" points");
}
}
ANY QUERIES COMMENT!
PLEASE UPVOTE!