skip to Main Content

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

3

Answers


  1. 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++;
     
    
    Login or Signup to reply.
  2. let count = 1;var a={},n=4;
      for (let row = 0; row < n; row++) {
        for (let col = row+1; col <=n; col++) {
            if(!a[col]){
                a[col]='';
            }
          a[col]+= count + ' ';
          count++;
        }
        console.log(a[row+1]);
      }
    
    Login or Signup to reply.
  3.   let arr = [];
      let val = 1;
    
      for (let i = 0; i < n; i++) {
        arr[i] = [];
        for (let j = 0; j < n - i; j++) {
          arr[i][j] = val;
          val++;
        }
      }
    
      let output = "";
    
      for (let i = 0; i < n; i++) {
        for (let j = 0; j <= i; j++) {
          output += arr[j][i - j] + " ";
        }
        output += "n";
      }
    
      console.log(output);
    }
    
    printIncrementalColumn(5);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search