Search code examples
javascripthtmlarraysmathsolution

Separating digits of a number


I am writing a program to receive a positive number and output each digit separately. For instance, if the input is 692, the program should output 2, 9, 6.

I have to use while loop and separate the digits using a modulus operator (%).

The digits should be separated without treating the number as a string and in a mathematical way.

Code:

HTML

<div class="column1">
    <div class="input">
      <button onclick="problem_09()"> Run the program </button>
    </div>
    <strong><p id="output"> </p></strong>
</div>

JAVASCRIPT

function problem_09() {
    var outputObj = document.getElementById("output");
    var a = parseInt(prompt("Please enter a number: ", ""));
    var digits = "";

    while(a >= 0){
        var d = a % 10;
        outputObj.innerHTML= "number: "+a+"<br><br>its digits: " + d;
        a = Math.floor(a/10);
    }
  
    outputObj.innerHTML = outputObj.innerHTML + "<br><br>" + "program ended";
    document.getElementsByTagName("button")[0].setAttribute("disabled","true");
}

Solution

  • Here is the solution:

    HTML:

    <div class="column1">
        <div class="input">
          <button onclick="problem_09()"> Run the program </button>
        </div>
        <strong><div id="output"> </div></strong>
      </div>
    
    

    JS:

    
    function problem_09() {
      var outputObj = document.getElementById("output");
      var a = parseInt(prompt("Please enter a number: ", ""));
      var digit = "";
      outputObj.innerHTML = ""
      while(a > 0){
        let num = a%10
        a = Math.floor(a/10)
        digit += "<p>"+num+"</p>"
      }
      outputObj.innerHTML = digit + "<br><br>" + "program ended";
      document.getElementsByTagName("button")[0].setAttribute("disabled","true");
    }
    

    Working Codepen: https://codepen.io/TheKetan2/pen/rNLOrGR

    OUTPUT:

    enter image description here