0
0
Cprogramming~30 mins

Defensive programming practices - Mini Project: Build & Apply

Choose your learning style9 modes available
Defensive programming practices
📖 Scenario: You are writing a small program that calculates the average of three test scores entered by a user. To make sure your program works well even if the user makes mistakes, you will use defensive programming practices.
🎯 Goal: Build a C program that safely reads three test scores, checks if they are valid (between 0 and 100), calculates the average only if all scores are valid, and prints the result.
📋 What You'll Learn
Create three integer variables to store test scores.
Create a helper variable to track if all inputs are valid.
Use if statements to check if each score is between 0 and 100 inclusive.
Calculate the average only if all scores are valid.
Print the average or an error message if any score is invalid.
💡 Why This Matters
🌍 Real World
Defensive programming helps prevent bugs and crashes by checking data before using it, which is important in real software that interacts with users or external data.
💼 Career
Many programming jobs require writing safe and reliable code that handles unexpected or incorrect inputs gracefully.
Progress0 / 4 steps
1
Create variables for test scores
Create three integer variables called score1, score2, and score3 and set them to 0.
C
Need a hint?

Use int to declare integer variables and assign 0 to each.

2
Add a variable to track input validity
Add an integer variable called valid and set it to 1 to assume inputs are valid initially.
C
Need a hint?

This variable will help us check if all scores are valid before calculating the average.

3
Check if scores are valid
Use three if statements to check if score1, score2, and score3 are each between 0 and 100 inclusive. If any score is outside this range, set valid to 0.
C
Need a hint?

Use logical OR || to check if a score is less than 0 or greater than 100.

4
Calculate and print average or error
If valid is 1, calculate the average of score1, score2, and score3 as a float variable average and print it with printf. Otherwise, print "Error: Invalid score(s)".
C
Need a hint?

Use printf with %.2f to print the average with two decimal places.