Introduction
Printing elements of an array in an alternate order is a very common task that can be efficiently accomplished in JavaScript. This problem can be solved by iterating through the array and printing elements at even indices starting from index 0.
Problem Statement
You are given an array A of size N. You need to print elements of A in an alternate order (starting from index 0).
Example 1:
Input:
N = 4
A[] = {1, 2, 3, 4}
Output:
1 3
Example 2:
Input:
N = 5
A[] = {1, 2, 3, 4, 5}
Output:
1 3 5
Your Task:
Since this is a function problem, you just need to complete the provided function void print(int ar[], int n)
Constraints:
1 <= N <= 105
1 <= Ai <= 105
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)
Solution Explanation
we have to print the elements of an array in an alternate way
let's say we have five numbers 1 2 3 4 5 6 7 8 so we have to print 1 3 5 7
In the given problem first test case has an array of size 4 and we have to print it in an alternate way starting from index 0. If we go with the logic of an even odd number, the number that will print is on the even number position which we are going to skip is on odd place, so here we are using the even-odd logic to solve this problem.
So if the element of the index is even then print the element.
Javascript Implementation
// code here
let output="";
Detailed Example
Consider an array [1, 2, 3, 4, 5]:
- Index 0: Element is 1 (even index, print it)
- Index 1: Element is 2 (odd index, skip it)
- Index 2: Element is 3 (even index, print it)
- Index 3: Element is 4 (odd index, skip it)
- Index 4: Element is 5 (even index, print it)