#  >> Standardized Tests >> SSAT

How do you write a program that prompt the user to enter five test scores and then prints average score?

Several programming languages can accomplish this. Here are examples in Python and JavaScript:

Python:

```python

Initialize a list to store the scores

scores = []

Use a loop to get five scores from the user

for i in range(5):

while True:

try:

score = float(input(f"Enter test score {i+1}: "))

if 0 <= score <= 100: # Check for valid input (0-100)

scores.append(score)

break

else:

print("Invalid score. Score must be between 0 and 100.")

except ValueError:

print("Invalid input. Please enter a number.")

Calculate the average

average = sum(scores) / len(scores)

Print the average

print(f"The average score is: {average:.2f}") # :.2f formats to 2 decimal places

```

JavaScript:

```javascript

let scores = [];

let sum = 0;

for (let i = 0; i < 5; i++) {

let score;

do {

score = parseFloat(prompt(`Enter test score ${i + 1}:`));

if (isNaN(score) || score < 0 || score > 100) {

alert("Invalid score. Score must be a number between 0 and 100.");

}

} while (isNaN(score) || score < 0 || score > 100);

scores.push(score);

sum += score;

}

let average = sum / scores.length;

console.log(`The average score is: ${average.toFixed(2)}`); // toFixed(2) formats to 2 decimal places

```

Both programs do the following:

1. Initialize: Create a list or array to store the scores. In Python, `scores = []` creates an empty list; in JavaScript, `let scores = [];` creates an empty array.

2. Input: Use a loop (either `for` or `while`) to prompt the user five times for test scores. Input validation is crucial – the code checks if the input is a number and within the range of 0-100. Error handling is included to catch invalid input.

3. Calculate: Sum the scores and divide by the number of scores to find the average.

4. Output: Print the calculated average, formatted to two decimal places for better readability.

Remember to choose the code that matches the programming language you're using. The Python version is more concise due to Python's built-in features for handling lists and input/output. The JavaScript version uses `prompt` and `alert` for user interaction, which are common in web browsers.

EduJourney © www.0685.com All Rights Reserved