Why is my C++ array output printing an extra name?

November 13, 2026 3 answers
Asked by frosting-by-committee

I have parallel arrays called scores and names, with their shared size in SIZE. I need to print each student whose score is above the average, but my output includes an extra name.

My code calculates the sum inside a loop over the names, then checks whether average is at least 100 before printing. What am I missing?

Answers

312ms_then_go

Calculate the average once, before you decide which names to print. Then loop through the arrays again and compare scores[i] to average. If scores[i] is greater, print names[i] followed by a newline.

The matching index is the key. Checking average against 100 does not tell you whether any particular student's score is above average. Use a strict greater than comparison, since a score equal to the average should not be printed.

frosting-by-committee:

So the second loop checks each score against the same average, rather than recalculating it for each name?

recheck-the-hatch:

Exactly. Sum all the scores first, divide by SIZE, then use that result for every comparison.

Reply to this answer
t4!route_602

There's another bug in the nested loops: sum is initialized only once, but the inner loop adds every score again on each pass through the outer loop. That makes your calculated average grow each time, which can make the 100 check start passing partway through the names.

For example, if the scores total 330, the running sum would become 330, then 660, then 990. Those later values aren't individual student scores. Moving the summing loop out of the name loop fixes the repeated accumulation.

Reply to this answer
2am_revision_desk

Try a small test you can check by hand, like scores of 60, 70, and 80. The average is 70, so only the name at index 2 should print. That also checks that a score equal to the average is excluded.

Temporary diagnostic output for the sum, average, index, and current score can help you see where things go wrong. Remove it before submitting if the required output contains only names.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions