-1

I want to make a reverse triangle using 'for' loop, which should look like this:

*****
 ****
  ***
   **
    *

This what I got:

*****
****
***
**
*

And this is my code:

function rightTriangle(n) {
  for (var i = 0; i <= n; i++) {
    for (var j = n - 1; j >= i; j--) {
      document.write('*');
    }
    document.write('<br>');
  }
}
rightTriangle(5);

Please help me out with this task, I would be so appreciated!

Rajesh
  • 21,405
  • 5
  • 35
  • 66
N. Jehnsen M
  • 101
  • 1
  • 10

3 Answers3

3

Add the below code to leave the intendation

for(var k=0; k<i; k++){
    document.write("&nbsp;");
}

function rightTriangle (n) {
    for (var i = 0; i <= n; i++) {
        for(var k=0; k<i; k++){
          document.write("&nbsp;");
        }
        for (var j = n-1; j >= i; j--) {
            document.write('*');
        }
        document.write('<br>');
    }
}
rightTriangle(5);
html{
  font-family:monospace;
}
Sagar V
  • 11,083
  • 7
  • 41
  • 62
1

function rightTriangle(n) {
  for (var i = 0; i <= n; i++) {
    for (var j = 0; j <= n; j++) {
      if(j>=i) document.write('*');
      else document.write('&nbsp&nbsp');
    }
    document.write('<br>');
  }
}
rightTriangle(5);
Mr.Bruno
  • 4,239
  • 2
  • 10
  • 24
0

Algo

  • Create n*n matrix with 2 values, " " and "*"
  • In html " " has no effect as extra spaces are trimmed. You will have to use &nbsp;, unicode value for single space.
  • Now loop and add necessary parts to string.
  • Since you need reverse triangle, spaces will come first. You can loop in ascending fashion with value of i denoting spaces and n-i denoting "*"

function rightTriangle(n) {
  var html = "";
  for (var i = 0; i < n; i++) {
    for(var j = 0; j< i; j++){
      html += "&nbsp;";
    }
    for(var k = 0; k< n-i; k++){
      html += "*"
    }
    html +="<br/>"
  }
  document.querySelector('.content').innerHTML = html
}
rightTriangle(5);
.content {
  font-family: monospace;
}
<div class="content"></div>

string.repeat

function rightTriangle(n) {
  var html = "";
  for (var i = 0; i < n; i++) {
    html += "&nbsp;".repeat(i) + "*".repeat(n - i) + "</br>"
  }
  document.querySelector('.content').innerHTML = html
}
rightTriangle(5);
.content {
  font-family: monospace;
}
<div class="content"></div>

Also note that using document.write and < br/>" are considered bad practice.

Community
  • 1
  • 1
Rajesh
  • 21,405
  • 5
  • 35
  • 66