Explanation
1. Purpose
This program iterates through an array of integer test scores, prints each individual score, and calculates and displays their average (mean).
2. Key Concepts
- Arrays: Storing multiple values of the same type in a single variable (
int[]). - Enhanced
forLoop (For-Each): A simplified loop used to iterate through array elements without needing an index variable. - Accumulator Pattern: Using a running sum variable (
total += score) to collect values during a loop. - Type Casting: Converting an
intto adouble((double) total) to perform floating-point division instead of integer division.
3. Code Walkthrough
- Initialization (
lines 3–4): An arrayscoresis populated with four numbers, and an accumulatortotalis set to0. - Iteration (
lines 6–9): Thefor (int score : scores)loop pulls each value from the array one at a time, adds it tototal, and prints it to the console. - Average Calculation (
line 10): Dividestotalbyscores.length(4). Castingtotalto(double)ensures the result includes decimal places rather than truncating the answer.
4. Output
Score: 72
Score: 91
Score: 84
Score: 63
Average: 77.5