Home > Software design >  Print alternatively one element from the last and one from the first (JavaScript)
Print alternatively one element from the last and one from the first (JavaScript)

Time:05-25

Print alternatively one element from the last and one from the first (JavaScript)

input 1, 3, 6, 3, 2, 8

output: 8, 1, 2, 3, 3, 6

CodePudding user response:

You can use the below approach

var array = [];
var size = prompt('Enter Array Size'); //Maximum Array size

for(var i=0; i<size; i  ) {
    
    //Taking Input from user
    array[i] = prompt('Enter Element '   (i 1));
}

//Print the array in the console.
console.log("Array Input: " array.join(','));

let output = [];
    let l = array.length - 1;
    for (let i = 0; i <= l; i  , l--) {
        if (i>=array.length/2) {
            console.log(array[i]);
            break;
        }
        output.push(array[l]);
        output.push(array[i]);
    }

console.log("Resultant Array: " output.join(','));

CodePudding user response:

Anyways you can try the below logic.

const input = [1, 3, 6, 3, 2, 8];
let output = [];
for (var i = 0; i < input.length / 2; i  ) {
  output.push(input[i]);
  output.push(input[input.length - (i   1)]);
}

  • Related