Skip to content
Advertisement

Print number patterns in JavaScript

I want to print numbers in pattern as below also I need this to print using only one for loop not in if condition inside for loop.

If I give s = 7 the output pattern would be 7, 5, 3, 1, 3, 5, 7

If s=6 then output is 6, 4, 2, 4, 6

This is what I tried but not successful.

const s = 7, b = 2

for (x = s, d = b; x > 0 && x <= 7; x -= 2) {
  console.log(x)
}

I don’t want to use any pre-built libraries to achieve this such as Math.abs()

Advertisement

Answer

With ternary operator:

const s = 10, b = 2

for (x = s, step = -b; x <= s; step = x + step <= 0 ? -step : step, x += step) {
  console.log(x)
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement