Problem overview
Version 4 of the Report Card project handles a whole class. Two parallel arrays describe it: names holds the students' names and scores holds their scores, and the value at position i in one belongs to the value at position i in the other. The program prints one line per student, with the name, a colon, a space and the letter grade.
The scale is the one from the previous version: 90 or more is an A, 80 to 89 a B, 70 to 79 a C, 60 to 69 a D, and anything lower an F. For the starting data the output is:
Alice: A
Bob: C
Carol: B
Dan: D
Approach: one loop, the same ladder inside
The new idea in this version is the loop. The grading ladder is the same if / else if / else chain as before, and it now runs once for each student.
The loop counts positions, not names. Position i reaches both names[i] and scores[i], so a counter from 0 up to names.length - 1 reads a name and its score together. That is why the loop condition is i < names.length: the last valid position is one less than the length.
Everything about one student, the score, the grade and the printed line, belongs inside the loop body. The body starts fresh on each pass, so the variables declared there exist only for the current student.
For the starting data the loop makes four passes:
| i | name | score | test that matches | grade |
|---|---|---|---|---|
| 0 | Alice | 92 | at least 90 | A |
| 1 | Bob | 78 | at least 70 | C |
| 2 | Carol | 85 | at least 80 | B |
| 3 | Dan | 67 | at least 60 | D |
Keeping names and scores in two arrays is simple, but it relies on discipline: the arrays must have the same length and the same order. Nothing in the language ties names[2] to scores[2]. Only the shared index does, so the program uses the same i for both reads and never sorts or edits one array without the other.
Step by step
- Write the loop. A
forloop withistarting at 0 and running whilei < names.length, adding one each time. Write the closing brace immediately, so that everything else goes between the braces. - Read the score. Inside the loop, store
scores[i]in aconstnamedscore. Aconstis fine here, since each pass creates a new one. - Declare the grade. A
letnamedgrade, typedstring, with no value yet. The ladder will assign it. - Start the ladder with
if (score >= 90), which sets"A". Checking the top grade first means every later test needs only a lower bound. - Add
else if (score >= 80)for"B". It runs only when the score is below 90. - Add
else if (score >= 70)for"C". - Add
else if (score >= 60)for"D". - Close with
elsefor"F". Every score below 60 ends up here, sogradealways gets a value. - Print the line after the ladder but still inside the loop:
names[i],": "andgrade, joined with+. Placing it inside the loop gives one line per student.
The solution in TypeScript
const names: string[] = ["Alice", "Bob", "Carol", "Dan"];
const scores: number[] = [92, 78, 85, 67];
for (let i = 0; i < names.length; i++) {
const score: number = scores[i];
let grade: string;
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";
}
console.log(names[i] + ": " + grade);
}
Details worth knowing:
- Array types.
string[]andnumber[]say what the arrays hold. The compiler uses them to check the code, and they are erased in the JavaScript that runs. - Block scope.
scoreandgradeare declared inside the loop body, so each pass gets its own pair. Theiin the loop header is also local to the loop. - Building the line.
names[i] + ": " + gradestarts with a string, so every+joins text. Since the whole line is one string, the output has the formAlice: A. - Indexing past the end. Reading an array position that doesn't exist gives
undefinedand no error.
Edge cases and common mistakes
<=instead of<.i <= names.lengthmakes one extra pass withiequal to 4. Both arrays areundefinedat that position, the ladder falls through to the finalelse, and the program prints an extra line,undefined: F, afterDan: D.- Arrays of different lengths. If
scoreshas only three entries, Dan's score isundefined. Every comparison withundefinedis false, so Dan gets an F: the output ends withDan: Fand no error is raised. - Printing outside the loop. If the
console.logline sits after the closing brace, it runs once, andgradeis out of scope there. The compiler reportsCannot find name 'grade', and the JavaScript that tsc still writes stops with aReferenceError. - Boundaries. With the scores 90, 89, 70 and 59, the output is A, B, C and F. A score exactly on a boundary goes to the higher grade because the tests use
>=. - Looping over the values.
for (const name of names)hands out the names but not their positions, so the matching score can't be found. When two arrays line up by position, loop over the positions.
Testing
- The starting data prints
Alice: A,Bob: C,Carol: BandDan: D, one per line. - Scores
[90, 89, 70, 59]printAlice: A,Bob: B,Carol: CandDan: F. - Scores
[92, 78, 85], one short, printDan: Fas the last line.
