Write a program to accept the name and total marks of N number of students in two single subscript arrays name[] and totalMarks[]. Calculate and print: (i) The average of the total marks obtained by N number of students. [average = (sum of total marks of all the students) / N] (ii) Deviation of each student’s total marks with the average. [deviation = total marks of a student - average]
Topic: Average and deviation using parallel arrays
Answer
import java.util.Scanner;
class Deviation { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter the number of students : "); int n = sc.nextInt(); sc.nextLine();
String name[] = new String[n]; int totalMarks[] = new int[n]; double sum = 0.0, avg;
for(int i = 0; i < n; i++) { System.out.print("Enter name : "); name[i] = sc.nextLine(); System.out.print("Enter total marks : "); totalMarks[i] = sc.nextInt(); sc.nextLine(); sum = sum + totalMarks[i]; }
avg = sum / n; System.out.println("Average of total marks = " + avg);
for(int i = 0; i < n; i++) System.out.println("Deviation of " + name[i] + " = " + (totalMarks[i] - avg)); } }
This question uses PARALLEL ARRAYS — two arrays whose index positions correspond, so name[i] and totalMarks[i] refer to the same student. Recognising that is the key idea, and it is why both arrays are created with the same size n.
Declare the arrays only AFTER reading n, since the size is not known until then. That is why new String[n] appears below the input statement.
Two details that decide correctness: - sum is declared double, so that sum / n gives a true average rather than an integer division. With both as ints, an average of 70.5 would come out as 70. - the extra sc.nextLine() after each nextInt() clears the leftover newline, without which the next name would be read as an empty string. Mixing nextInt() and nextLine() catches out a great many candidates.
Note that the deviation may be negative, which is correct and expected — it shows the student scored below the average.
Check with marks 80, 60 and 70: the average is 70.0 and the deviations are 10.0, -10.0 and 0.0.
n int - number of students name[] String[] - names of the students totalMarks[] int[] - total marks of the students sum double - running total of all the marks avg double - average of the total marks i int - loop variable sc Scanner - object used to read input