In: Computer Science
Define a problem with user input, user output, While Statement and some mathematical computation. Write the pseudocode, code and display output.
Problem statement: Finding the average of a student subject marks entered by the user. The average is the sum of the marks, divided by the total number of subjects. The program will ask the user to enter one student subject detail marks at a time. It will keep count of the number of integers entered, and it will keep a running total of all the number of subjects it has read so far. This will be done by using while statement.
pseudocode:
Let avg // The avg of the integers entered by the user. Let sum=0 // The avg of the integers entered by the user. Let total_subject = 0 // The number of subjects entered by the user. while there are more subjectmarks to process: Read an subject_marks Add it to the sum Count the total_subject Divide sum by total_subject to get the average of all subject Print out the average
code:
import java.util.*;
public class Main {
public static void main(String[] args) {
int subject_marks; // subject_marks input by the user.
int sum; // The sum of the subject_marks.
int total_subjects; // The number of subjects.
double average; // The average of the subject_marks.
Scanner s=new Scanner(System.in);
/* Initialize the summation and counting variables. */
sum = 0;
total_subjects = 0;
/* Read and process the user's input. */
System.out.print("Enter your first subject_marks: ");
subject_marks = s.nextInt();
while (subject_marks != 0) {
sum += subject_marks; // Add inputNumber to running sum.
total_subjects++; // Count the input by adding 1 to count.
System.out.print("Enter your next subject_marks, or 0 to quit the program: ");
subject_marks = s.nextInt();
}
/* Display the result. */
if (total_subjects == 0) {
System.out.println("You didn't enter any subject_marks!");
}
else {
average = ((double)sum) / total_subjects;
System.out.println();
System.out.printf("Their average is %1.3f.\n", average);
}
} // end main()
} // end class
output