Skip to content Skip to sidebar Skip to footer

Print Number Patterns In Javascript - Ascending And Descending In Same Loop

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 0,1,2

Solution 1:

functionprintNumbers(s){
   for (i = 0, num = 0; i <= s * 2; ++i <= s ? num++ : num--){
       console.log(num);
   }
}

printNumbers(7);

Top down version with steps support:

functionprintNumbers(s, step){
   for (i = 0, num = s; num <= s; i+= step, i <= s ? num -= step : num += step) {
       console.log(num);
   }
}

printNumbers(7, 2);

You can try it with different steps.

Solution 2:

// 0,1,2,3,4,5,6,7,6,5,4,3,2,1,0functionprint(num) {
  let c = 0let output = []
  while(c <= num) {
    output.push(c)
    c++
  }
  
  while(num > 0){
   num--
   output.push(num)
  }
  
  return output.join(',')
}

let o = print(7)

console.log(o)

Solution 3:

Try this :

const s = 10let solution= ''for ( x=0,step=1; x!== -1 ; x===s ? (step = -1, x = x+step): x= x+step) {
    solution = solution + `${x},`
}
solution = solution.slice(0,-1)
console.log(solution)

Solution 4:

You could take a single loop with a correction for values greater than the largest value.

function* print(n, s) {
    for (let i = 0; i <= 2 * n; i += s) {
        yield i > n ? 2 * n - i : i;
    }
}

console.log(...print(7, 1));
console.log(...print(7, 2));

Solution 5:

Recapping a little bit your requirements:

  • Single for
  • No use of arrays
  • No use of if
    • for that matter, the ternary operator (c)?a:b translates to if (c) a; else b
  • If I give s = 7 the output pattern would be 0,1,2,3,4,5,6,7,6,5,4,3,2,1,0

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

Here is a code for that:

let i = 0;
const s = 7;
let stringToPrint = ''+s;
for (i=s-1; i>=0; i--){
    stringToPrint = ''+i+','+stringToPrint+','+i;
}
console.log(stringToPrint)

Post a Comment for "Print Number Patterns In Javascript - Ascending And Descending In Same Loop"