sudh na
sudh na

Reputation: 41

Print Triangle using javascript function

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

*
**
***

Upvotes: 4

Views: 14777

Answers (10)

Amrish khan Sheik
Amrish khan Sheik

Reputation: 101

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.

Upvotes: 1

Akshay Kumar
Akshay Kumar

Reputation: 467

Center Tringle

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

Upvotes: 0

Michael Kamau
Michael Kamau

Reputation: 11

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

Upvotes: 0

Yash Thakor
Yash Thakor

Reputation: 129

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

Upvotes: 1

Moez Ben Rebah
Moez Ben Rebah

Reputation: 312

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)

Upvotes: 0

akhtarvahid
akhtarvahid

Reputation: 9769

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

Upvotes: 0

user3409214
user3409214

Reputation: 11

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.

Upvotes: 1

Exception_al
Exception_al

Reputation: 1079

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

Upvotes: 3

Adelin
Adelin

Reputation: 8209

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

Upvotes: 2

Ele
Ele

Reputation: 33726

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

Upvotes: 1

Related Questions