Problem overview
The previous version graded one score. This version grades a whole class. The program starts with two arrays that line up by position: names holds the students' names, and scores holds their scores. Position 0 of both arrays describes Alice, position 1 describes Bob, and so on. The program prints one line per student, in the form name: grade, using the same scale as before: 90 and above is A, 80 to 89 is B, 70 to 79 is C, 60 to 69 is D, and anything lower is F.
For the starting data the output is:
Alice: A
Bob: C
Carol: B
Dan: D
Approach: one loop over the positions
Because the two arrays are linked by position, the loop should count positions, not walk one array. A for loop with an int counter i from 0 to names.Length - 1 gives you an index that works for both arrays: names[i] is the student and scores[i] is that student's score.
The body of the loop is the letter-grade ladder from the previous version, applied to scores[i]. Read the score into a local variable score first, so the ladder reads the same as before. Then declare grade, let the ladder assign it, and print the student's name, a colon, a space and the grade.
The ladder is evaluated again on every pass. Variables declared inside the loop body, here score and grade, exist only for that pass: each iteration starts with fresh variables, and the previous student's grade cannot leak into the next one.
A trace of the first two iterations shows the flow. For i = 0, the score is 92, the first test succeeds, the grade is "A" and the line Alice: A is printed. For i = 1, the score is 78: the tests for 90 and 80 fail, the test for 70 succeeds, and the line is Bob: C.
Step by step
- Write the loop header.
for (int i = 0; i < names.Length; i++)starts at 0 and stops beforenames.Length, the number of students. Arrays count from 0, so the last valid index is one less than the length. - Read the score. Inside the loop,
int score = scores[i];takes the score at the same position as the name. - Declare
gradeas astringwithout a value. The ladder will give it one. - Start the ladder with
if (score >= 90)and assign"A". Always check from the highest grade down: each later test then needs only a lower limit. - Add the
else ifbranches for 80 (B), 70 (C) and 60 (D). A branch is reached only when the ones before it failed, so the 80 test means 80 to 89. - End with
elsefor the F. Every pass through the ladder now assignsgrade, which is what lets C# accept the use ofgradeafterwards. - Print inside the loop, after the ladder:
names[i] + ": " + grade. Being inside the loop, the line runs once per student, which gives the four lines of output.
The solution in C#
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";
}
Console.WriteLine(names[i] + ": " + grade);
}
Details worth knowing:
- Arrays have a fixed length.
names.Lengthis a property, with no parentheses, and it never changes after the array is created. AList<T>usesCountinstead and can grow. - Array initializers.
string[] names = {"Alice", ...};creates the array and fills it in one declaration. The compiler counts the elements for you. - Looping on the length of one array. The code trusts that
scoreshas at least as many elements asnames. C# checks every array access at run time, so a shorterscoresarray throws anIndexOutOfRangeExceptionwith the message "Index was outside the bounds of the array." instead of reading garbage. - String joining. In
names[i] + ": " + gradeevery piece is a string, so+simply concatenates them.
Edge cases and common mistakes
- Using
<=in the loop condition.i <= names.Lengthmakes one extra pass withi = 4, andscores[4]throws anIndexOutOfRangeException. - Arrays of different lengths. With three names and two scores, the program prints the first two students and then throws on the third. The data must be kept in step.
- Empty arrays. With no students, the loop body never runs and the program prints nothing, which is correct.
- Printing after the loop. A print line placed after the closing brace of the loop does not compile, because
gradeandiexist only inside the loop. The print belongs in the loop body. - Boundary scores. A score of exactly 90 is an A, and exactly 60 is a D, so keep
>=in the tests.
Testing
Try changing the arrays:
- Names Eve, Finn and Gus with scores 90, 59 and 60 print
Eve: A,Finn: FandGus: D. - Two empty arrays print nothing.
The next version builds on this one.
