windmaomao
windmaomao

Reputation: 7661

Print triangle shape with star symbol

I wonder how do I show my kids how to print a triangle shape with basic symbol.

I started with this code

for (i = 1; i <= 5; i++) {
  const strs = []
  for (j = 0; j < i; j++) {
    strs.push('*')
  }
  console.log(strs.join(''))
}

But I want to get

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

or worst case skip the non-formatting row,

  *

 ***
  
*****

Upvotes: 1

Views: 284

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76434

This is how you can achieve your goal

var spaces = "  ";
for (i = 1; i <= 5; i++) {
  if (i % 2 == 1) spaces = spaces.substring(0, spaces.length - 1);
  const strs = []
  for (j = 0; j < i; j++) {
    strs.push('*')
  }
  console.log(spaces + strs.join(''))
}

enter image description here

Even better if you ask me:

for (i = 1; i <= 5; i++) {
  var strs = []
  for (j = 0; j < i; j++) {
    strs.push('*')
  }
  j = 5 - j;
  strs = strs.join("");
  while (j-- > 0) strs = " " + strs;
  console.log(strs)
}

enter image description here

Or even much, much better:

var spaces = "    ";
for (i = 1; i <= 5; i++) {
  const strs = []
  for (j = 0; j < i; j++) {
    strs.push('* ')
  }
  console.log(spaces + strs.join(''))
  spaces = spaces.substring(0, spaces.length - 1);
}

enter image description here

Upvotes: 2

Vineet Kumar Gupta
Vineet Kumar Gupta

Reputation: 535

for (i = 1; i <= 5; i++) {
const strs = []
for(x=1;x <= 2-i; x++){
strs.push(' ')
}
for (j = 0; j < i; j++) {
strs.push('*')
}
console.log(strs.join(''))
}

Upvotes: 0

Shankar S
Shankar S

Reputation: 405

I just wrote an algo,

int starBase = N;

for(int i=0; i<N; i++){
    // print prefix spaces (formating)
    for(int k=0; k<(i-N);k++){
        print(" ");
    }

    // print *
    for(int j=0; j<i;j++){
        print("* ");
    }
    
    // new line
    print ("\n")
}

with N=5 your should work look like this. its just a pseudo code you may have to convert it to your prefered langauge.

0
1     * 
2    * *
3   * * * 
4  * * * *

Upvotes: 1

Related Questions