DEV Community

Abhishek Gupta
Abhishek Gupta

Posted on

How to Print Alternate Elements of an Array in JavaScript (DSA)

🧩 Problem: Alternate Elements of an Array

Given an array arr[], your task is to print every alternate element of the array starting from the first element.

In other words, print elements at index 0, 2, 4, ... and skip the rest.


📥 Input

An array of integers arr[]

📤 Output

Print the alternate elements of the array (starting from index 0)


🧪 Examples

Example 1:

Input: arr[] = [10, 20, 30, 40, 50]
Output: 10 30 50
Enter fullscreen mode Exit fullscreen mode

Explanation:
Print the first element (10), skip the second (20), print the third (30), skip the fourth (40), and print the fifth (50).


Example 2:

Input: arr[] = [-5, 1, 4, 2, 12]
Output: -5 4 12
Enter fullscreen mode Exit fullscreen mode

⚠️ Constraints

  • 1 ≤ arr.length ≤ 10^5
  • -10^9 ≤ arr[i] ≤ 10^9

Solution

Approch 1

Top comments (0)