I am trying to figure out a triangle excercise where the user inputs a number and the triangle is then created based on said number ex enter 5 This is what I want
**5
6 6
7 7 7
8 8 8 8
9 9 9 9 9
10 10 10 10 10**
Each line the number is increased by 1. I can't get my code to increase by 1. I keep getting
5
5 5
5 5 5
5 5 5 5
5 5 5 5 5
Anyone have any suggestions? Thanks
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (i = 1; i <= 6; i ) {
//loop 2
for (y = 0; y < i; y ) {
document.write(num);
}
document.write(num = num 1; "<br>");
}
<p id="num"> </p>
CodePudding user response:
You just have to use the entered number as the loop upper limit:
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (i = 1; i <= num; i ) {
//loop 2
for (y = 0; y < i; y ) {
document.write(num);
}
document.write("<br>");
}
CodePudding user response:
This syntax is entirely invalid:
document.write(num = num 1; "<br>");
You're somehow confusing calling a function with defining a for
loop. Those are two entirely different things.
Don't randomly try to munge together separate operations. Put each operation on its own line of code. The two operations you want to perform are:
- Add 1 to
num
- Output a
<br>
element
These are separate operations. So separate them:
num = num 1;
document.write("<br>");
CodePudding user response:
You don't seem to be placing the incrementation of your num before writing it to the document. See the code below check the line between loops.
let num = prompt("Enter a number");
//Check if its a number
num = parseInt(num);
//loop 1
for (let i = 1; i <= 6; i ) {
//loop 2
num ;
for (let y = 0; y < i; y ) {
document.write(num);
}
document.write("<br>");
}
<p id="num"> </p>;