Print alternate elements of an array

Introduction

Print alternate elements of an array



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 <= A<= 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="";

    for(let i=0; i<arr.length; i++){
        
        if(i%2===0){
            output=output+arr[i]+" ";
        }
    }console.log(output);
    
  }
}

//arr[i] is our elements and 'i' is our  index  
 
so let there be an array =[1,2,3,4,5,6,7]

here array[1] is our element and  the index is zero for arry[1]
so the index starts from 0  and the elements start from 1.


Detailed Example

Consider an array [1, 2, 3, 4, 5]:

Start iterating from index 0:
  • 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)
Output: 1 3 5

Code Testing

Test the function with different inputs to ensure its correctness:

printAlternateElements([1, 2, 3, 4], 4); // Output: 1 3
printAlternateElements([1, 2, 3, 4, 5], 5); // Output: 1 3 5
printAlternateElements([10, 20, 30, 40, 50, 60], 6); // Output: 10 30 50


Conclusion

This simple yet effective approach allows you to print elements of an array in an alternate order starting from index 0. The solution is optimized for performance and follows best coding practices. By implementing this function, you can handle arrays efficiently in JavaScript, ensuring both clarity and efficiency in your code.

For more tutorials and coding solutions, make sure to follow our blog and stay updated with the latest programming practices!

Post a Comment

Previous Post Next Post