Skip to content
Advertisement

How to make a triangle using for loop javascript

I have a simple question although i cannot manage to resolve this problem. Hope you can help. I need to make triangle using for loop and from this 4 exercises I don’t know what to do with the third one. I haven’t used Javascript before, so any help would be appreciated.

enter image description here

 # # # # #
   # # # #
     # # #     <----- here is triangle i need to make. Just in case 
       # #
         #

var i;
var j;
for (i = 0; i <= 5; i++ )
{
document.write("</br>");
for ( j = 0; j < 6-i; j++ )
{
document.write( "&nbsp&nbsp" );
}
for ( j = 6-i; j <= 5; j++ )
{

document.write( "*" );
}
}

This is code I wrote for D in photo. And I’m sorry i did not add it at first.

Advertisement

Answer

I’m sure there are better solutions (simply left-padding with spaces comes to mind), but here’s the quick and dirty one I created from your own solution.

  for (var i = 0; i < 5; i++) {
    for (var j = 0; j < i; j++) {
      document.write("&nbsp;&nbsp;&nbsp;");
    }
    for (var j = 5; j > i; j--) {
      document.write("#");
      if (j > i + 1) document.write("&nbsp;");
    }
    document.write('<br/>')
  }

https://js.do/code/diamondsinthesky

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement