Ke.
Ke.

Reputation: 2586

Print sequence of numbers in javascript

I'm sure this is quite a simple programming question however, I cant seem to understand it...

I'm trying to make the console.log print out numbers like this - 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 - one for each line. I thought modulo could be used to make this happen, however, I cant seem to figure out how to use it.

Here is the code:

iteration = 16;

for (var i = 0; i < iteration; i++) {
    if(i == iteration%4 )
    console.log(i);
}

Upvotes: 1

Views: 2162

Answers (2)

Emidio Torre
Emidio Torre

Reputation: 1253

I suggest that you use two nested for loops, one for the rows and another one for the columns.

Here's an example of how i would do it:

const columns = 4;
const rows = 4;

//if you want to just console.log each number on a different line
for (let i = 1; i <= rows; i++) {
  for (let j = 1; j <= columns; j++) {
    console.log(i);
  }
  console.log("\n");
}

//if you want to add each number to an array, and then log the array
for (let i = 1; i <= rows; i++) {
  let columnsArray = [];
  columnsArray.length = columns;
  columnsArray.fill(i);
  console.log(columnsArray);
}

//if you want to just log the numbers, you can spread the array
for (let i = 1; i <= rows; i++) {
  let columnsArray = [];
  columnsArray.length = columns;
  columnsArray.fill(i);
  console.log(...columnsArray);
}

//or you could push the arrays in another one, and get a matrix!
const matrix = [];
for (let i = 1; i <= rows; i++) {
  let columnsArray = [];
  columnsArray.length = columns;
  columnsArray.fill(i);
  matrix.push(columnsArray);
}
console.log(matrix);

It was not clear the output that you wanted, so i got a little sidetracked and made an example for the different cases that came to my mind.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386806

Yes, you need a single loop.

No, you do not need the remainder operator %. This would give you

0 1 2 3 0 1 2 3 ...

But instead you could divide the actual value by 4 and take the integer value for console.log.

const iteration = 16;

for (let i = 0; i < iteration; i++) {
    console.log(Math.floor(i / 4) + 1); // offset for starting with 1
}

Upvotes: 2

Related Questions