In: Computer Science
Java
Write a program to record the GPAs of a class and find the percentage of students in each GPA. The program first allows the user to enter the number of students enrolled in the class, and then to enter the GPA of all students one by one. For each student, the input must be between 1 and 4 inclusively. Otherwise, the software displays a message as “Invalid number!” and asks for a new GPA for the same student
Enter number of students: 8 Enter GPA for student #1 is: 1 Enter GPA for student #2 is: 5 Invalid number! Enter GPA for student #2 is: 2 Enter GPA for student #3 is: 3 Enter GPA for student #4 is: 4 Enter GPA for student #5 is: 4Enter GPA for student #6 is: 2 Enter GPA for student #7 is: 3 Enter GPA for student #8 is: 4 |
The total number of students is 8. ***************** GPA 3 --- 2 student(s) |
Note: you should trace the GPA list just once. So, you should use an array GPAFreq with four elements; to store the frequencies of each GPA from 1 to 4.
The program is given below: that take number of students from user, take GPA for student from user (between 1 to 4 inclusively), if entered GPA is not in between 1 to 4 inclusively then ask again, print total number of students, print GPA frequency, then print percentage of student in GPA.
import java.util.*;
public class Main
{
public static void main(String[] args) {
int n,i;
Scanner sc=new Scanner(System.in);
//take number of students from user
System.out.print("Enter number of students: ");
n=sc.nextInt();
int[] GPA_s=new int[n];
int[] GPAFreq=new int[4];
//execute for loop upto number of students
for(i=0;i<n;i++)
{ //take GPA for student from user between 1 to 4
inclusively
System.out.printf("Enter GPA for student #%d is:
",(i+1));
GPA_s[i]=sc.nextInt();
//if entered GPA is not in between 1 to 4
inclusively
while(!(GPA_s[i]>=1 &&
GPA_s[i]<=4))
{ //then print Invalid number
System.out.println("Invalid number!");
//ask again
System.out.printf("Enter GPA for student #%d is:
",(i+1));
GPA_s[i]=sc.nextInt();
}
//if GPA is 1
if(GPA_s[i]==1)
{ //increment GPAFreq[0] by 1
GPAFreq[0]+=1;
}
//if GPA is 2
else if(GPA_s[i]==2)
{ //increment GPAFreq[1] by 1
GPAFreq[1]+=1;
}
//if GPA is 3
else if(GPA_s[i]==3)
{ //increment GPAFreq[2] by 1
GPAFreq[2]+=1;
}
//if GPA is 4
else if(GPA_s[i]==4)
{ //increment GPAFreq[3] by 1
GPAFreq[3]+=1;
}
}
//print total number of students
System.out.println("\nThe total number of students is
"+n+".");
System.out.println("*****************");
//print GPA frequency
for(i=0;i<4;i++)
{
System.out.println("GPA "+(i+1)+" --- "+GPAFreq[i]+"
student(s)");
}
System.out.println("*****************");
//print percentage of student in GPA
for(i=0;i<4;i++)
{
float ans=((GPAFreq[i]*100)/(float)n);
System.out.printf("\nThe percentage of students with
GPA (%d) is (%.1f%%).",i+1,ans);
}
}
}
The screenshot of code is given below:
Output: