Alternate elements of an array
Last Updated :
04 Dec, 2024
Given an array arr[], the task is to print every alternate element of the array starting from the first element.
Examples:
Input: arr[] = [10, 20, 30, 40, 50]
Output: 10 30 50
Explanation: Print the first element (10), skip the second element (20), print the third element (30), skip the fourth element(40) and print the fifth element(50).
Input: arr[] = [-5, 1, 4, 2, 12]
Output: -5 4 12
Iterative Approach
The idea is to start iterating from index 0, print the element at that index, and then increment the index by 2 to move to the next alternate element. Keep on printing the elements till we reach the end of the array.
C++
// Iterate C++ Program to print alternate elements
// of the array
#include <iostream>
#include <vector>
using namespace std;
vector<int> getAlternates(vector<int> &arr) {
vector<int> res;
// Iterate over all alternate elements
for(int i = 0; i < arr.size(); i += 2) {
res.push_back(arr[i]);
}
return res;
}
int main() {
vector<int> arr = {10, 20, 30, 40, 50};
vector<int> res = getAlternates(arr);
for(int x: res)
cout << x << " ";
}
C
// Iterate C Program to print alternate elements
// of the array
#include <stdio.h>
void getAlternates(int arr[], int n) {
// Iterate over all alternate elements
for(int i = 0; i < n; i += 2) {
printf("%d ", arr[i]);
}
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
getAlternates(arr, size);
return 0;
}
Java
// Iterate Java Program to print alternate elements
// of the array
import java.util.*;
class GfG {
static ArrayList<Integer> getAlternates(int[] arr) {
ArrayList<Integer> res = new ArrayList<>();
// Iterate over all alternate elements
for (int i = 0; i < arr.length; i += 2) {
res.add(arr[i]);
}
return res;
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
ArrayList<Integer> res = getAlternates(arr);
for (int x : res) {
System.out.print(x + " ");
}
}
}
Python
# Iterate Python Program to print alternate elements
# of the array
def getAlternates(arr):
res = []
# Iterate over all alternate elements
for i in range(0, len(arr), 2):
res.append(arr[i])
return res
if __name__ == "__main__":
arr = [10, 20, 30, 40, 50]
res = getAlternates(arr)
print(" ".join(map(str, res)))
C#
// Iterate C# Program to print alternate elements
// of the array
using System;
using System.Collections.Generic;
class GfG {
static List<int> getAlternates(int[] arr) {
List<int> res = new List<int>();
// Iterate over all alternate elements
for (int i = 0; i < arr.Length; i += 2) {
res.Add(arr[i]);
}
return res;
}
static void Main() {
int[] arr = { 10, 20, 30, 40, 50 };
List<int> res = getAlternates(arr);
foreach (int x in res) {
Console.Write(x + " ");
}
}
}
JavaScript
// Iterate JavaScript Program to print alternate elements
// of the array
function getAlternates(arr) {
let res = [];
// Iterate over all alternate elements
for (let i = 0; i < arr.length; i += 2) {
res.push(arr[i]);
}
return res;
}
// Driver Code
const arr = [10, 20, 30, 40, 50];
const res = getAlternates(arr);
console.log(res.join(" "));
Time Complexity: O(n), where n is the number of elements in arr[].
Auxiliary Space: O(1)
Recursive Approach
We can also print the alternate elements using recursion. We start from index = 0, that is the first element of the array and print its value. We then call the recursive function again with the (index + 2) as the current index.
C++
// Recursive C++ Program to print alternate elements
// of the array
#include <iostream>
#include <vector>
using namespace std;
// Recursive function to store all alternate elements
void getAlternatesRec(vector<int> &arr, int idx, vector<int>& res) {
if(idx < arr.size()) {
res.push_back(arr[idx]);
getAlternatesRec(arr, idx + 2, res);
}
}
vector<int> getAlternates(vector<int> &arr) {
vector<int> res;
getAlternatesRec(arr, 0, res);
return res;
}
int main() {
vector<int> arr = {10, 20, 30, 40, 50};
vector<int> res = getAlternates(arr);
for(int x: res)
cout << x << " ";
}
Java
// Recursive Java Program to print alternate elements
// of the array
import java.util.ArrayList;
class GfG {
// Recursive function to store all alternate elements
static void getAlternatesRec(int[] arr, int idx,
ArrayList<Integer> res) {
if (idx < arr.length) {
res.add(arr[idx]);
getAlternatesRec(arr, idx + 2, res);
}
}
static ArrayList<Integer> getAlternates(int[] arr) {
ArrayList<Integer> res = new ArrayList<>();
getAlternatesRec(arr, 0, res);
return res;
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
ArrayList<Integer> res = getAlternates(arr);
for (int x : res) {
System.out.print(x + " ");
}
}
}
Python
# Recursive Python Program to print alternate elements
# of the array
# Recursive function to store all alternate elements
def getAlternatesRec(arr, idx, res):
if idx < len(arr):
res.append(arr[idx])
getAlternatesRec(arr, idx + 2, res)
def getAlternates(arr):
res = []
getAlternatesRec(arr, 0, res)
return res
if __name__ == "__main__":
arr = [10, 20, 30, 40, 50]
res = getAlternates(arr)
print(" ".join(map(str, res)))
C#
// Recursive C# Program to print alternate elements
// of the array
using System;
using System.Collections.Generic;
class GfG {
// Recursive function to store all alternate elements
static void getAlternatesRec(int[] arr, int idx,
List<int> res) {
if (idx < arr.Length) {
res.Add(arr[idx]);
getAlternatesRec(arr, idx + 2, res);
}
}
static List<int> getAlternates(int[] arr) {
List<int> res = new List<int>();
getAlternatesRec(arr, 0, res);
return res;
}
static void Main() {
int[] arr = { 10, 20, 30, 40, 50 };
List<int> res = getAlternates(arr);
foreach (int x in res) {
Console.Write(x + " ");
}
}
}
JavaScript
// Recursive JavaScript Program to print alternate
// elements of the array
// Recursive function to store all alternate elements
function getAlternatesRec(arr, idx, res) {
if (idx < arr.length) {
res.push(arr[idx]);
getAlternatesRec(arr, idx + 2, res);
}
}
function getAlternates(arr) {
let res = [];
getAlternatesRec(arr, 0, res);
return res;
}
// Driver Code
let arr = [10, 20, 30, 40, 50];
let res = getAlternates(arr);
console.log(res.join(" "));
Time Complexity: O(n), where n is the number of elements in arr[].
Auxiliary Space: O(n), for recursive call stack.
Similar Reads
Deleting Elements in an Array - Array Operations In this post, we will look into deletion operation in an Array, i.e., how to delete an element from an Array, such as:Delete an Element from the Beginning of an ArrayDelete an Element from a Given Position in an ArrayDelete First Occurrence of Given Element from an ArrayRemove All Occurrences of an
4 min read
Inserting Elements in an Array - Array Operations In this post, we will look into insertion operation in an Array, i.e., how to insert into an Array, such as:Insert Element at the Beginning of an ArrayInsert Element at a given position in an ArrayInsert Element at the End of an ArrayInsert Element at the Beginning of an ArrayInserting an element at
2 min read
Searching Elements in an Array | Array Operations In this post, we will look into search operation in an Array, i.e., how to search an element in an Array, such as:Searching in an Unsorted Array using Linear SearchSearching in a Sorted Array using Linear SearchSearching in a Sorted Array using Binary SearchSearching in an Sorted Array using Fibonac
15+ min read
Array Rearrangement Arrays are fundamental data structures in programming, allowing us to store and manipulate collections of related data. One common operation we may need to perform on arrays is rearranging their elements. Array rearrangement can serve various purposes, such as sorting the elements, reversing the ord
3 min read
What are Subsequences in an Array? Subsequences are a fundamental concept in computer science and programming when working with arrays. A subsequence of an array is a sequence of elements from the array that appear in the same order, but not necessarily consecutively. In this blog post, we'll discuss subsequences, covering their defi
6 min read
Applications, Advantages and Disadvantages of Array Array is a linear data structure that is a collection of data elements of same types. Arrays are stored in contiguous memory locations. It is a static data structure with a fixed size. Applications of Array Data Structure:Arrays mainly have advantages like random access and cache friendliness over o
2 min read