skip to Main Content

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


  1. 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.

    let num = prompt("Enter a number to see the sum of its digits:");
    
    // Just check for input at this point. Doesn't matter yet if it's a number or not.
    if (!num) {
        alert("please enter a number");
    } else {
        let sum = 0;
        for (let i = 0; i < num.length; i++) {
            // The prepended + is an implicit way to convert a string to a number
            sum = sum + +num[i];
        }
        console.log(sum);
        alert("The result is : " + sum);
    }
    Login or Signup to reply.
  2. You cannot iterate on a variable which is of number type.
    The correct code will be :-

    let num = prompt("Enter a number to see the sum of its digits:");
    if (!Number(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);
    }
    
    Login or Signup to reply.
  3. 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):

    let num = Number(prompt("Enter a number to see the sum of its digits:"));
    if (isNaN(num)) {
        alert("please enter a number");
    } else {
        const numString = num.toString(); // Convert it to a string
        let sum = 0;
        for (let i = 0; i < numString.length; i++) {
            // Convert the char (string) to a number to make the sum work
            sum = sum + Number(numString.charAt(i));
        }
        console.log(sum);
        alert("The result is : " + sum);
    }

    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).

    Login or Signup to reply.
  4. function sumOfDigit(num) {
    return num.toString().split("")
        .reduce((sum, digit) =>
            sum + parseInt(digit), 0);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search