Home > database >  javascript how to print star pattern on same line
javascript how to print star pattern on same line

Time:01-29

I want to print diamond pattern using *. Please find the code below:

for (let i=0; i<num; i  ) {
    let str="";
    for (let j=i; j<num; j  ) {
        str ="*";
    }
    console.log(str);
}

for (let i=num; i>0; i--) {
    let spaces=num-i;
    let spacesStr="";
    for (let j=0; j<spaces; j  ) {
        spacesStr =" ";
    }
    let str=spacesStr;
    for (let j=i; j>0; j--) {
        str ="*";
    }
    console.log(str);
}

The output of the above code is as below:

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

I know that if I start printing both the patterns from line 1 I can achieve the desired output. But not sure how I can do that. Please let me know.

thanks

CodePudding user response:

You've quite figured out the answer already. You will need 3 for loops inside your main loop inorder to get that pattern.

let num = 5;
let string = "";

for (let i = 0; i <= num; i  ) {
  // printing star
  for (let j = 0; j < num - i; j  ) {
    string  = "*";
  }
  // printing spaces
  for (let k = 0; k < i * 2; k  ) {
    string  = " ";
  }

  // printing stars
  for (let l = num - i; l > 0; l--) {
    string  = "*";
  }
  string  = "\n";
}

console.log(string);

First, we print the left stars, then we print the spaces, and then again we print the right stars.

CodePudding user response:

The idea is to build each line.

First, let's focus on the top half of the diamond.

  • On the first line, there are n stars, 0 spaces, n stars.
  • On the second line, there are n-1 stars, 2 spaces, n-1 stars.
  • On the third line, there are n-2 stars, 4 spaces, n-2 stars.
  • And the pattern follows till there are 0 stars.

Now, coming to the bottom half of the diamond, the pattern is same, just reversed. So, for the inner loops, you can just change i to n-i and n-i to i.

const n = 5;
const star = "*";
const space = " ";

// Top half of the diagram
for (let i = 0; i < n; i   ) {
  let pattern = ''
  for (let j = 0; j < (n - i); j  ) pattern  = star;
  for (let j = 0; j < i; j  ) pattern  = `${space}${space}`;
  for (let j = 0; j < (n - i); j  ) pattern  = star;
  console.log(pattern);
}

// Bottom half of the diagram
for (let i = 1; i <= n; i   ) {
  let pattern = ''
  for (let j = 0; j < i; j  ) pattern  = star;
  for (let j = 0; j < (n - i); j  ) pattern  = `${space}${space}`;
  for (let j = 0; j < i; j  ) pattern  = star;
  console.log(pattern);
}
  •  Tags:  
  • Related