Home > other >  How to print thunder star pattern in JavaScript
How to print thunder star pattern in JavaScript

Time:03-10

i have a task to do thunder star pattern loop that look like this

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

I can only work up to this part

$n = 5;
for($i = 1; $i <= $n; $i  ) {
 for($j = 1; $j <= $n; $j  ) {
  if($i == $j) {
    document.write(" * ");
  } 
  else {
    document.write("&nbsp;&nbsp;&nbsp;");
  }
}
  document.write("<br/>");
}

what can i do to work this out?

thank you in advance, and please dont put minus on me :D thank you!

CodePudding user response:

const diagonalLine = (n) => {
  let line = '';

  for (let i = 0; i < n; i  ) {
    for (let j = 0; j < i; j  ) {
      line  = ' ';
    }
    line  = '*\n';
  }
  return line;
};
const line = (n) => {
  let line = '';

  for (let i = 0; i < n; i  ) {
    line  = '*';
  }
  return line;
};
const printPattern = n => `${diagonalLine(n)}${line(n)}${diagonalLine(n)}`;

console.log(printPattern(5));

CodePudding user response:

can be achieved by adding one way by one more variable for looping of pattern

$n = 5;
$count = 1; // added for looping pattern
for($i = 0; $i <= $n; $i  ) {
 for($j = 1; $j <= $i; $j  ) {
  if($i == $j&& $i != $n ) {
    document.write(" * ");
  }if($i == $n && $j < $n && $count > 0){
   document.write(" * ");
  }else {
    document.write("&nbsp;&nbsp;&nbsp;");
  }
}
if($i == $n && $j == ($n   1 ) && $count > 0)
  {
   $j=1;
   $i=0;
   $count--;
  }
  document.write("<br/>");
}

  • Related