4

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

*
**
***
3
  • What is the output you are getting ? What do you expect ? Commented Feb 22, 2018 at 14:35
  • don't forget about .repeat(), so that you don't double your loops Commented Feb 22, 2018 at 14:36
  • 3
    You will have to add "\n" in outer loop using line += "\n" Commented Feb 22, 2018 at 14:36

10 Answers 10

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much for reply, i am unable to get the logic of printing next line statement ----> line += "\n". so once the inner loop prints the first line "*" and when it condition false the cursor will jump to come out from loop and i did not understand how the cursor is going down it should be iterating in the nested loop itself until outer loop condition fails. i am sorry am not getting logic behind it.
I edited my response to clarify a bit. ... does it help ?
Kindly mark the response as an answer if it help you
Simply click the green tick mark beside the answer ... Where you can also vote the answer up
@sudhna you accepted my answer. I think you meant to accept this answer instead
2

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

1 Comment

this above example is pretty clear with single loop . thank you all for your responses
1

The \n was at an incorrect position.

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

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

Comments

1
function hashTriangle(length)
{
let str="";
for(let i=0;i<length;i++) 
    {

    str+="#";
    console.log(str);
    }
}
hashTriangle(7);

console.log() prints a new line. So it is not necessary for nested loops and confusing newline characters to be appended to our string.

Comments

1

function makeLine(length) {
     var line = "";
     for (var i = 1; i <= length; i++) {
       for (var j = 1; j <= i; j++) {
           line += "*";
       }
       // add new line after loop is completed
       line = line + "\n"
    }
    return line + "\n";
}
console.log(makeLine(5));

you need to add \n to line when the inner loop is completed

Comments

1
const printTriangle=(symbol,gapSymbol,num) =>{
    // const num =25;
    let gap = 1;
    const Sgap = symbol+' ';
    for(i= num-1;i>=0;i--){
        let prefixSuffix=''
        prefixSuffix = gapSymbol.repeat(i);
        let line = ''
        if(i == num -1){
           line = gapSymbol.repeat(i)+symbol+gapSymbol.repeat(i);
        }
        if(i != num -1 && i !=0){
            line = gapSymbol.repeat(i)+symbol+gapSymbol.repeat(gap)+symbol+gapSymbol.repeat(i);
            gap = gap+2;
        }
        if(i<1){
            line = ''+Sgap.repeat(1)+Sgap.repeat(num-2)+Sgap.repeat(1);
        }
        console.log(line)
    }
}

printTriangle('*','.',15)

This is a JavaScript function that generates a triangle shape using the console.log method. The function takes in three parameters:

symbol: the character to be used to draw the triangle gapSymbol: the character to be used as a gap in between the symbols num: the size of the triangle (the number of symbols on the base) The function starts by initializing the variable gap with the value 1 and Sgap as a string of symbol followed by a space. It then uses a for loop to iterate num number of times, starting from num - 1 down to 0.

For each iteration of the loop, the function uses a single line variable to store the string to be logged. The prefixSuffix variable is used to store the repeated gapSymbols, which are used in each iteration of the loop.

The logic for each iteration is controlled by conditional statements, which determine the shape to be drawn based on the value of i. If i is equal to num - 1, the line is constructed using a single symbol surrounded by repeated gapSymbols. If i is not equal to num - 1 and i is not equal to 0, the line is constructed using repeated gapSymbols, a symbol, a gap of repeated gapSymbols, and another symbol, all surrounded by repeated gapSymbols. If i is less than 1, the line is constructed using repeated Sgaps.

Finally, the constructed line is logged using the console.log method.

Comments

0

Simple solution using padStart, padEnd, repeat method for printing right and left triangle

Left triangle

const printLeftTriangle = (n) => {
  let output='';
  for (let i = 1; i <= n; i++) {
   output +="*".repeat(i).padStart(n) + "\n";
  }   
  return output;
}

console.log(printLeftTriangle(5));

Right triangle

const printRightTriangle = (n) => {
 let output='';
 for (let i = 1; i <= n; i++) {
  output +="*".repeat(i).padEnd(n) + "\n";
 }   
 return output;
}

console.log(printRightTriangle(5));

Comments

0

try this solution please:

const halfTriangle = N => {
  for (let row = 0; row < N; row++) {
    let line = "";
    for (let col = 0; col <= N; col++) {
      if (col <= row) {
        line += '#';
      } else {
        line += ' '
      }
    }
    console.log(line);
  }
}

halfTriangle(4)

Comments

0

// creates a line of * for a given length
function makeLine(length) {
  let line = "";
  for (var j = 1; j <= length; j++) {
    line += "* ";
  }
  return line + "\n";
}

// your code goes here.  Make sure you call makeLine() in your own code.
function buildTriangle(length) {
  // Let's build a huge string equivalent to the triangle
  var triangle = "";

  //Let's start from the topmost line
  let lineNumber = 1;

  for (lineNumber = 1; lineNumber <= length; lineNumber++) {
    // We will not print one line at a time.
    // Rather, we will make a huge string that will comprise the whole triangle
    triangle = triangle + makeLine(lineNumber);
  }
  return triangle;
}

// test your code 
console.log(buildTriangle(10));

Comments

0

Center Tringle

let line='';
for(let i=1; i<=5;i++){
  line += ' '.repeat(5-i)
  line += '*'.repeat(i+i-1)+'\n'
}
console.log(line);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.