Problem overview
Version 4 grades a whole class. Two parallel arrays describe it: names holds the students' names and scores holds their scores, and the same position in both arrays belongs to the same student. For each student the program prints the name, a colon, a space and the letter grade.
The grading scale is the one from version 3: 90 or more is A, 80 to 89 is B, 70 to 79 is C, 60 to 69 is D, and below 60 is F. For the starting data the output is four lines:
Alice: A
Bob: C
Carol: B
Dan: D
Approach: one loop over positions, the ladder inside
Version 3 already has the ladder that turns one score into one grade. What is new is doing it once per student. A for loop that counts positions does this: the counter i goes from 0 up to the last position, and at each pass names[i] and scores[i] are the matching pair.
This is why the loop counts positions and doesn't use the enhanced for over just one array. With only for (int s : scores) the program would have the score but no way to find the name next to it. The index connects the two arrays.
Everything that depends on one student, the score, the grade and the print, goes inside the loop body, so that it repeats for each student.
Step by step
- Write the loop.
for (int i = 0; i < names.length; i++)visits positions 0, 1, 2 and 3. Arrays have alengthfield, written without parentheses, and the conditioni < names.lengthstops before the first position that doesn't exist. Close the loop's brace right away so the later lines go inside it. - Read the score. Declare
int score = scores[i];inside the loop. The sameireads the score that belongs to the name at that position. - Declare
grade.String grade;goes inside the loop with no value, because the ladder will assign it. - Start the ladder at the top.
if (score >= 90)sets"A". Starting with the highest grade means each later test needs only a lower limit. - Add the B branch with
else iffor 80 or more. This test runs only when the score is below 90. - Add the C branch for 70 or more.
- Add the D branch for 60 or more.
- End with
else. It sets"F", sogradehas a value after every pass. - Print inside the loop. After the ladder, print
names[i], the text": "andgrade. Because the print is inside the loop, it runs once per student, which gives the four lines.
The solution in Java
String[] names = {"Alice", "Bob", "Carol", "Dan"};
int[] scores = {92, 78, 85, 67};
for (int i = 0; i < names.length; i++) {
int score = scores[i];
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else if (score >= 60) {
grade = "D";
} else {
grade = "F";
}
System.out.println(names[i] + ": " + grade);
}
Java details that matter here:
- Variables inside the loop are new on every pass.
scoreandgradeare declared in the loop body, so each pass starts with fresh variables. That is whygradedoesn't need a starting value and can't carry a stale grade from the previous student. - Two array types.
String[]holds the names andint[]the scores. The braces in{"Alice", ...}are an array initializer that sets the length from the number of elements. - Printing with
+.names[i] + ": " + gradejoins three strings. The text": "contains the colon and the space that the output format asks for.
Complexity
Time: O(n), where n is the number of students. The loop makes one pass, and the ladder does at most four comparisons per student, which is a constant amount of work.
Space: O(1) beyond the input. The loop keeps a few variables, and the output is printed as it is produced, not collected.
Edge cases and common mistakes
- Off-by-one in the condition. Writing
i <= names.lengthmakes the loop run once too often. Reading a position that doesn't exist throwsArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4on a four-element array. - Arrays of different lengths. The loop is driven by
names.length. Ifscoreshas fewer elements thannames, the program prints the students that have a score and then fails withArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3. - Printing outside the loop. A
printlnafter the closing brace runs once. It would also not compile there, sincegradeandscoreexist only inside the loop. - An empty class. With empty arrays the condition is false from the start, the body never runs and nothing is printed.
- Boundary scores. A score of 90 is an A and 60 is a D, while 59 is an F. For the data 100, 90, 59, 60 and 0 the grades come out A, A, F, D and F.
Testing
Try these in the editor above, and compare the output with the table:
| Names and scores | Output |
|---|---|
| Alice 92, Bob 78, Carol 85, Dan 67 | A, C, B, D |
| Eve 100, Finn 90, Gus 59, Hana 60, Ivy 0 | A, A, F, D, F |
| no students | no output |
