Doubt with Floyd’s Triangle

Asked

Viewed 98 times

0

I have a problem with this code:

function calculate() {
  var input = document.getElementById("input").value;
  var x = input;
  for (var i = input; i > 1; i--) {
    x += i;
  }
  var j = 1;
  var k = 1;
  var number = 1;
  var output;
  while (k < x) {
    output = number.toString() + " ";
    number += 1;
    if (number = j) {
      output += "\n";
      j = 1;
      k++;
    }
  }
  document.getElementById("output").innerHTML = output;
}
<input id="input" type="number" />
<button onclick="calculate()">Calculate</button><br/>
<span id="output"></span>

It always returns 1. Can anyone please help me?

  • 1

    Why not edit the question and describe what the code should do?

  • 2

    if (number == j) instead of if(number = j) you are testing and not assigning... And yet, you have an infinite loop in your algorithm, do a table test.

  • Then see that the solution is much simpler https://www.rushis.com/floyds-triangle-javascript-code/

  • The value entered in input will define what?

1 answer

0


<input id="input" type="number" />
<button onclick="calculate()">Calculate</button><br/>
<span id="output"></span>

<script>
function calculate() {

var input = document.getElementById("input").value;
var x = input;


  var string;
  var increm=1;
  var i;

for(i=0;i<x;i++){
  string = "";

  var j=0;

  while(j<= i){
        output += string + "    " + increm;
        j++;
        increm++;
}
output+= "<br>";
}

  document.getElementById("output").innerHTML = output;
}
</script>
  • Please explain your answer. What is trivial to you may not be trivial to others.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.