I saw a bunch of other posts on this topic but none in javascript. here is my code.
var theNumber = function digitAdd (base, exponent) {
var number = 1;
for (i=0; i < exponent; i++) {
var number = base * number;
}
return number
}
function find(theNumber) {
var sum=0;
parseInt(theNumber);
while(theNumber>0)
{
sum=sum+theNumber%10;
theNumber=Math.floor(theNumber/10);
}
document.writeln("Sum of digits "+sum);
}
find(theNumber (2, 50));
I am getting the correct answer, I just don't fully understand the 2nd function, namely the while statement. Any help would be greatly appreciated. Thanks!
i use this :
Update (ES6 syntax) :
i use it :)
without eval
The second function uses the modulo operator to extract the last digit:
When the last digit is extracted, it is subtracted from the number:
And the number is divided by
10
:Each time this loop repeats, the last digit is chopped off and added to the sum.
The modulo operator returns the single digit if the left hand side is smaller than the right (which will happen for any 1-digit number), which is when the loop breaks:
This is how the leading digit gets added to the total.
A less numeric alternative would be this:
It does literally what you are trying to do, which is iterate over the digits of the number (by converting it to a string).
Not sure what you meant, In case you were asking about while loop..
The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.
The while loop here is extracting digits one by one from the actual number and adding those. Try to do each step manually and you will get it.