+ 1
Please could someone help make the output of the loop in my code to be only the sum of the last loop. Thanks.
9 ответов
+ 8
// Just place console.log statement outside the loops.
var sum=0;
for ( p = 0; p <=10; p++) {
var notPrime = false;
for ( i = 2; i <= p; i++) {
if (p%i===0 && i!==p) {
notPrime = true;
}
}
if (notPrime === false) {
sum+=p;
}
}
console.log(sum);
+ 1
thank you hatsy but could you please explain why it happened with the log outside the loop
+ 1
Everything that is inside the loop happens on each iteration of the loop. If you put it outside to loop it will only happen when the loop is finished.
+ 1
okay thanks Kevin. I appreciate
+ 1
I tried encapsulating that code in the script tag in html using two different ide (bracket and dream weaver) but it couldn't run. you have any idea why it can't run?
+ 1
if you are copying these exact codes into a HTML page between the script tags then it is working. I am assuming you are running it on the chrome browser. if you right click on the blank page and then go to inspect. On the tabs you should see tabs (elements, console,..etc.)
click on the console and you will see the 18 there.
"console.log();" outputs to that console tab.
+ 1
When you are are using document.write(); you have to write it like you would any HTML content. Write it in this form and see if is the way you want it.
document.write("<h1> The sum is: " + sum + "</h1>");
0
thanks Kevin but when I changed it to document.write ,I still had a blank page.
0
k thanks would try it out