Question 5: Write a program to input name and percentage of 35 students of class X in two separate one dimensional arrays. Arrange students details according to their percentage in the descending order using selection sort method. Display name and percentage of first ten toppers of the class.
Java Programming Language (Article) (Program)
13
Given Input:
Expected Output:
Program:
import java.util.Scanner;
public class RAnsariStudentPercentage
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
//Initialize the 2 SDA
String names[] = new String[35];
double percentage[] = new double[35];
/*
* Accept student details from user and store
* in corresponding SDA
*/
for (int i = 0; i < names.length; i++) {
System.out.print("Enter name of student "
+ (i + 1) + ": ");
names[i] = in.nextLine();
System.out.print("Enter percentage of student "
+ (i + 1) + ": ");
percentage[i] = in.nextDouble();
in.nextLine();
}
//Selection Sort in Descending Order
for (int i = 0; i < percentage.length - 1; i++) {
int maxIdx = i;
for (int j = i + 1; j < percentage.length; j++) {
if (percentage[j] > percentage[maxIdx])
maxIdx = j;
}
double t = percentage[i];
percentage[i] = percentage[maxIdx];
percentage[maxIdx] = t;
String name = names[i];
names[i] = names[maxIdx];
names[maxIdx] = name;
}
//Display first ten toppers
System.out.println("Name\tPercentage");
for (int i = 0; i < 10; i++) {
System.out.println(names[i] + '\t' + percentage[i]);
}
}
}
Output:
This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.
Program:
import java.util.Scanner; public class RAnsariStudentPercentage { public static void main(String args[]) { Scanner in = new Scanner(System.in); //Initialize the 2 SDA String names[] = new String[35]; double percentage[] = new double[35]; /* * Accept student details from user and store * in corresponding SDA */ for (int i = 0; i < names.length; i++) { System.out.print("Enter name of student " + (i + 1) + ": "); names[i] = in.nextLine(); System.out.print("Enter percentage of student " + (i + 1) + ": "); percentage[i] = in.nextDouble(); in.nextLine(); } //Selection Sort in Descending Order for (int i = 0; i < percentage.length - 1; i++) { int maxIdx = i; for (int j = i + 1; j < percentage.length; j++) { if (percentage[j] > percentage[maxIdx]) maxIdx = j; } double t = percentage[i]; percentage[i] = percentage[maxIdx]; percentage[maxIdx] = t; String name = names[i]; names[i] = names[maxIdx]; names[maxIdx] = name; } //Display first ten toppers System.out.println("Name\tPercentage"); for (int i = 0; i < 10; i++) { System.out.println(names[i] + '\t' + percentage[i]); } } }
Output:
This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.