Calculates Grades and Displays the Student Average:class ClassAverage’s main method (lines 7–31) implements the class-averaging algorithm described by the pseudocode in Fig. 4.7—it allows the user to enter 10 grades, then calculates and displays the average.
Java Program to Calculate Grade of Students
// Fig. 4.8: ClassAverage.java
// Solving the class-average problem using counter-controlled repetition.
import java.util.Scanner; // program uses class Scanner
public class ClassAverage
{
public static void main(String[] args)
{
// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);
// initialization phase
int total = 0; // initialize sum of grades entered by the user
// processing phase uses counter-controlled repetition
while ( ) // loop 10 times
{
System.out.print("Enter grade: "); // prompt
int grade = input.nextInt(); // input next grade
total = total + grade; // add grade to total
}
// termination phase
int average = total / 10; // integer division yields integer result
// display total and average of grades
System.out.printf("%nTotal of all 10 grades is %d%n", total);
System.out.printf("Class average is %d%n", average);
}
} // end class ClassAverage
Output of Program
Enter grade: 67
Enter grade: 78
Enter grade: 89
Enter grade: 67
Enter grade: 87
Enter grade: 98
Enter grade: 93
Enter grade: 85
Enter grade: 82
Enter grade: 100
Total of all 10 grades is 846
Class average is 84