Advertisement
3vo

Process Odd Numbers of Array

3vo
Jun 14th, 2023
600
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*You are given an array of numbers. Write a function that prints the elements at odd positions from the array,
  2. doubled and in reverse order.
  3. The input comes as an array of number elements.
  4. The output is printed on the console on a single line, separated by space.
  5. Examples:
  6. Input
  7. [10, 15, 20, 25]
  8. Output
  9. 50 30
  10. Input
  11. [3, 0, 10, 4, 7, 3]
  12. Output
  13. 6 8 0
  14. Hints
  15. Counting in arrays starts from 0
  16. For example –we receive 10, 15, 20, 25
  17. The elements at odd positions are 15 (index 1) and 25 (index 3)
  18. We need to take these two elements and multiply them * 2
  19. Finally, we print them on the console in reversed order */
  20. //Here's a JavaScript function that satisfies the requirements you've described:
  21.  
  22. function printDoubledElementsInReverse(arr) {
  23.   let result = [];
  24.   for (let i = 1; i < arr.length; i += 2) {
  25.     let doubled = arr[i] * 2;
  26.     result.push(doubled);
  27.   }
  28.   console.log(result.reverse().join(" "));
  29. }
  30.  
  31.  
  32. /*This function takes an array of numbers as input, and iterates over it starting at the second element (`i = 1`). For each odd position, it doubles the corresponding element and adds it to a `result` array. After iterating over the input array, it reverses the `result` array and prints its elements, separated by spaces.*/
  33.  
  34. //Here's an example usage of the function with the input array `[10, 15, 20, 25]`:
  35.  
  36.  
  37. printDoubledElementsInReverse([10, 15, 20, 25]); // Output: "50 30"
  38.  
  39. //In this example, `printDoubledElementsInReverse()` outputs `"50 30"`, which corresponds to the doubled elements at odd positions in //the input array (`15 * 2` and `25 * 2`), in reverse order.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement