# Not getting correct result when solving a challenge

I am trying to solve this coding challenge
Result that I need

`````` 1 8 9 16 17
2 7 10 15 18
3 6 11 14 19
4 5 12 13 20
``````

logic for colindex that is even
rowsNumber * colIndex+1 // 4*0+1 which gives 1 for column 0 row 1

logic for colindex that is odd
rowsNumber*(colIndex+1); // 4*(1+1) which gives 8 for column 2 row 1

``````const rowsNumber = 4;
const columnsNumber = 5;

for(let i=0;i<rowsNumber;i++) {

for(let j=0;j<columnsNumber;j++) {
if(j%2 == 0) {
console.log(rowsNumber*j+1);
}   else {
console.log(rowsNumber*(j+1))
}
}

}
``````

I am getting following result

``````1
8
9
16
17
1
8
9
16
17
1
8
9
16
17
1
8
9
16
17
``````

What am I doing wrong?

### >Solution :

Your logic is only valid for first row. You’ll also have to consider the rowIndex.
The actual logic is
For even rows : rowsNumber * (colIndex+1) – rowIndex
For odd rows : rowsNumber * colIndex+1 + rowIndex
So the code would be as follows

``````const rowsNumber = 4;
const columnsNumber = 5;
for(let i=0;i<rowsNumber;i++) {
for(let j=0;j<columnsNumber;j++) {
if(j%2 == 0) {
console.log(rowsNumber*j+1+i);
}   else {
console.log(rowsNumber*(j+1)-i)
}
}
}
``````

This gives the output as :

``````1
8
9
16
17
2
7
10
15
18
3
6
11
14
19
4
5
12
13
20
``````