+ 4

var a=1234; sum=0; while (a){ sum+=a%10; a=(a-a%10)/10; } alert (sum); //output:10 how this can output 10? Any explanation?

Javasicrip

26th Dec 2018, 12:05 PM
Hafsa Mohamed
Hafsa Mohamed - avatar
2 odpowiedzi
+ 8
Here, loop will run until a become 0(false). And every time sum+=a%10 statement add last digit to sum. So in first loop sum+=4, second sum+=3, third sum+=2, fourth sum+=1 and now sum is 10. The second statement is used to remove digit which is the once added from a.
26th Dec 2018, 12:10 PM
Raj Chhatrala
Raj Chhatrala - avatar
+ 4
Raj Chhatrala thank you very much
26th Dec 2018, 12:15 PM
Hafsa Mohamed
Hafsa Mohamed - avatar