The snippets of JavaScript below contain syntax errors and/or logic errors. Iden
ID: 3931999 • Letter: T
Question
The snippets of JavaScript below contain syntax errors and/or logic errors. Identify the errors and insert your corrected code.
a-
function main()
{
var score;
var total;
for(i = 0; i < 5; i++)
{
score = getScore(score);
total = computeTotal(total, score);
}
console.log("The total of all the exams is " + total);
}
function getScore (score)
{
score = Number(prompt("Enter your exam score"));
return score;
}
function computeTotal (total, score)
{
total = total + score;
return total;
}
main();
b.
function main()
{
var num;
var endProgram = 0;
while (endProgram = 0)
{
num = Number(prompt("Enter a number to be squared"));
num = num * num;
console.log("Your number squared is " + num);
endProgram = Number(prompt("Enter y to square another number"));
}
}
main();
c.
function main()
{
var avg;
var total = 0;
var num;
var ctr = 0
do
{
num = Number(prompt("Enter a number"));
total = total + num;
}
while (ctr < 5)
avg = total / ctr;
console.log("The average of your numbers is " + avg);
}
main();
d.
function main()
{
for (i = 0, i < 10, i++)
{
console.log ("The value of i is " + i);
}
}
main();
e.
function main()
{
var billAmt = 0;
var billTotal = 0;
var moreBills = 1;
do while(moreBills == 1)
{
billAmt = Number(prompt("Enter the amount of your bill"));
billTotal = billTotal + billAmt;
moreBills = Number(prompt("Enter 1 if you have another bill to process"));
}
console.log("Your bill total is " + billTotal);
}
main();
Explanation / Answer
Here is the solution for problem a.
function main()
{
var score;
var total = 0;
for(i = 0; i < 5; i++)
{
score = getScore(score);
total = computeTotal(total, score);
}
console.log("The total of all the exams is " + total);
}
function getScore (score)
{
score = Number(prompt("Enter your exam score"));
return score;
}
function computeTotal (total, score)
{
total = total + score;
return total;
}
main();
The variable total should be initialized to 0, unless otherwise, it will contain a garbage value.
The solution for problem b:
function main()
{
var num;
var endProgram = 'y';
while (endProgram == 'y')
{
num = Number(prompt("Enter a number to be squared"));
num = num * num;
console.log("Your number squared is " + num);
endProgram = prompt("Enter y to square another number");
}
}
main();
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.