Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Triangle using javascript function

Tags:

javascript

function makeLine(length) {
  var line = "";
  for (var i = 1; i <= length; i++) {
    for (var j = 1; j <= i; j++) {
      line += "*";

    }

  }
  return line + "\n";
}
console.log(makeLine(2));

I am trying to print triangle, i dont know where i am doing wrong, can some please explain the logic behind printing triangle using nested loops

*
**
***
like image 344
sudh na Avatar asked Oct 31 '25 09:10

sudh na


2 Answers

After you finish printing a line, you need to add a newline "\n" so that you move to the next line. You could do this as below :

function makeLine(length) {
  // length has the number of lines the triangle should have
  var line = "";
  for (var i = 1; i <= length; i++) {
    // Enter the first for loop for the number of lines
    for(var j=1; j<=i; j++){ 
      // Enter the second loop to figure how many *'s to print based on the current line number in i. So the 1st line will have 1 *, the second line will have 2 *s and so on.
      line += "*";
    }
    // Add a newline after finishing printing the line and move to the next line in the outer for loop
    line+="\n";

  }
  // Print an additional newline "\n" if desired.
  return line + "\n";
}
console.log(makeLine(2));
like image 89
Exception_al Avatar answered Nov 02 '25 23:11

Exception_al


don't forget about .repeat()

function makeLine(length) {
  var line = "";
  for (var i = 1; i <= length; i++) {
    line+="*".repeat(i)+"\n";
  }
  return line;
}
console.log(makeLine(3));
like image 25
Adelin Avatar answered Nov 02 '25 22:11

Adelin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!