+ 1
Please break this down
// I am self teaching js now Iām with the loops and came across this example, I have no idea how the code outputs 55 can someone please break it down in simple English. To me I counted output to be 11 let count =1; let total =0; while (count <= 10){ total = total + count; count = count + 1; } document.write(total);
5 Answers
+ 2
This is now cristal clear ššæ
+ 1
You are a star thank you very much
0
šš
This code can be written shorter:
//count is 1
let count = 1;
//the total is 0
let total = 0;
//loop finishes when count reaches 10
while(count <= 10) {
Ā Ā Ā //nests count value in total, and adds them
Ā Ā Ā total += count;
Ā Ā Ā //increase count value one by one
Ā Ā Ā count++;
}
//prints total (the sum of printed counts
document.write(total);
//1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
/*
output:
55
*/
You increase count value one by one, and add it to total variable. So this happens when you write total += count:
total = 0; now total is 0
Loop starts
total = 1 + 0 = 1; now total is 1
total = 2 + 1 = 3; now total is 3
total = 3 + 3 = 6; now total is 6
total = 4 + 6 = 10; now total is 10
total = 5 + 10 = 15; now total is 15
total = 6 + 15 = 21; now total is 21
total = 7 + 21 = 28; now total is 28
total = 8 + 28 = 36; now total is 36
total = 9 + 36 = 45; now total is 45
total = 10 + 45 = ; now total is 55
Loop finished
Printing total = printing 55
If you needed more informations, contact me on Sololearn.
0
Happy coding š
- 1
https://code.sololearn.com/Wv3lJnu2B13Q/?ref=app
I believe it fills ur need to understand each iterations ^^