showing the sum of the digits in JS

  Kiến thức lập trình

I just need help with a simple problem in JS.
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);
}

Thank U, as a beginner.

the program resulted in 0 number as the sum of digits and it’s, it’s just not working

New contributor

محمدرضا صادقی is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT