How to print alternate elements of an array in Java
Problem statement
You are given an array of size N. You need to print elements for the given array in an alternate order, starting from index 0.
Example
Input:
arr = {11,12,13,14}
Output:
- 11 13
Explanation
Since we need to start from index 0, we print 11, skip 12, and print 13.
Solution
-
Initialize the array
arrwith input numbers as11, 12, 13, 14, 15. -
Find array length
n, withlengthproperty on the array. -
Use the
forloop to traverse the array. -
Start with index
0, go until the last element, and increment index by2every time to skip alternate elements. -
Print element.
When the loop ends, we will have printed all the alternate elements in the array.
Code
class Solution {public static void main( String args[] ) {//initialize arrayint[] arr = {11, 12, 13, 14, 15};//array lengthint n = arr.length;// loop through the array and increment by 2for(int i=0; i<n; i = i+2){//print elementSystem.out.println(arr[i]);}}}
Time and space complexity
This solution takes time complexity, as we traverse elements in the array once.
The solution then takes space complexity, as we are not taking extra space to solve this problem aside from the input array.