1

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);
}
3
  • 1
    Can you please edit your question and add the formatted output you expect? It's not clear (at least to me), where you expect the linebreaks. Commented Dec 5, 2020 at 10:05
  • use another for loop. nest this within the new loop. and make a line break in the outer loop using "\n" Commented Dec 5, 2020 at 10:07
  • I can't understand what you mean by "one for each line." As @Mureinik said, please show what you mean in a well-formatted way. Commented Dec 5, 2020 at 10:08

2 Answers 2

2

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
}

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.