I get a number from the user and i want to calculate the sum of its digits. here’s the code:
let num = Number(prompt("Enter a number to see the sum of its digits:"));
if (isNaN(num)) {
alert("please enter a number");
} else {
let sum = 0;
for (let i = 0; i < num.length; i++) {
sum = sum + num[i];
}
console.log(sum);
alert("The result is : " + sum);
}
the program resulted in 0 number as the sum of digits and it’s, it’s just not working
4
Answers
You are converting the
prompt
input to a number and then trying to loop through the number as if it was an array (which it is not). Instead, leave the input as a string and loop over that array-like object and only convert the individual digits when doing the math.You cannot iterate on a variable which is of number type.
The correct code will be :-
The reason it’s not working is because, during the loop, you’re basically treating
num
as if it was a string, but it’s actually always a number.Here’s a working code (without changing too much of your code):
Note: in this case,
.charAt()
may be a little safer than the bracket notation, because it always returns a string (here’s a detailed explanation).