The first part of the program is the Collector. Instead of us telling the computer the scores upfront, we’ve programmed it to ask, then after 5 input continuously, we use an If-Else Chain to filter the average through a series of checkpoints.
What To Understand Clearly:
The Loop: We use a for loop because we know exactly how many times we need to ask (5 times).
The Conversation: The prompt() function pauses the program and waits for the user.
The Conversion: Computers often see user input as "text" (strings). We use parseFloat() to tell the computer to **treat **the input as a number so we can do math with it.
Running Total: Every time a score comes in, we immediately add it to totalSum, It’s like a teacher adding marks to a ledger one by one.
'''Javascript
let scores = [];
let numberOfSubjects = 5;
let totalSum = 0;
for (let i = 0; i < numberOfSubjects; i++) {
let input = prompt("Enter score for subject " + (i + 1) + ":");
let score = parseFloat(input);
scores.push(score);
totalSum += score;
}
let average = totalSum / numberOfSubjects;
let grade;
if (average >= 70) {
grade = "A (Excellent)";
} else if (average >= 60) {
grade = "B (Very Good)";
} else if (average >= 50) {
grade = "C (Credit)";
} else if (average >= 45) {
grade = "D (Pass)";
} else {
grade = "F (Fail)";
}
'''
console.log("Total Score: " + totalSum);
console.log("Average Score: " + average);
console.log("Final Grade: " + grade);
*SUMMARY *
When you run this code on your computer, laptop or phone, you aren't just calculating numbers, you are creating a workflow ✅.
Input: You input the raw data into the system.
Logic: The system organizes and calculates the data.
Output: The computer (system) gives a well readable and understandable result (The Grade).
TAKE NOTE: This is the fundamental structure of almost every professional application.
From Input → Processing → Output.
Can we add a feature that prevents the user from entering a number higher than 100, or calculate the GPA on a 5.0 scale.
Top comments (0)