Hello I’m just trying to understand why Im getting 55 as the result from this code Im new lerning while loops, thanks guys
var sum = 0;
var num = 0;
while (num <= 10) {
sum += num;
num++;
}
console.log(sum);
Hello I’m just trying to understand why Im getting 55 as the result from this code Im new lerning while loops, thanks guys
var sum = 0;
var num = 0;
while (num <= 10) {
sum += num;
num++;
}
console.log(sum);
var sum = 0;
var num = 0;
while (num <= 10) {
sum += num;
num++;
}
console.log(sum);
Here in this code the value of num is updating everytime from 1 to 10.
If you try calculating the loop sum= 0 but num = 1+2+4+5+6+7+8+9+10, you will be getting 55.
To understand it much better try changing the value of this
while (num <= 10)
to
while (num <= 4)
You’ll get 10, as the value of num gets added.
It works like this
0(sum) = 0 + 1 + 2+ 3+ 4;
Hi,
Initially, the value of sum
and num
is 0
.
For every iterations, there’re 2 things happens:
num
is added to sum
( sum += num
means sum = sum + num
)num
increased its value by 1
( num++
means num = num + 1
)The value of num
goes from 0 to 1, to 2, to 3 … to 10 then stops.
So sum = 0 + 1 + 2 + 3 + ... + 10 = 55
.
55
is the last value of sum
after the loop ended.
thanks lot this concept its much more clear now
thank you very much toan
thanks for your help very useful