Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript number pattern print

How to print the below pattern using javascript

n = 4

1
2 5
3 6 8
4 7 9 10

I tried the below code but it print the incremental number in row

const pattern = (n) => {
  let count = 1;
  for (let row = 0; row < n; row++) {
    for (let col = 0; col <= row; col++) {
      document.write(count + " ");
      count++;
    }
    document.write("<br/>");
  }
};

pattern(4);

but the expectation is to print incremental number in col

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are almost on goal.. you just a small fix: pretty simple and basic

const pattern = (n) => {
  let count = 1;
  for (let i = 1; i <= n; i++) {
    let row = "";
    let currentNum = count;
    for (let j = 1; j <= i; j++) {
      row += currentNum + " ";
      currentNum += (n - j) ;
    }
    console.log(row);
    count++;
  }
};

pattern(4);

and as your example
instead of console.log you can do

document.write("<br/>");
document.write(row);
count++;
 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading