7) Python program to print the elements of an array present on even position
In this program, we need to print the element which is present on even position. Even positioned element can be found by traversing the array and incrementing the value of i by 2.
In the above array, elements on even position are b and d.
ALGORITHM:
-
STEP 1: Declare and initialize an array.
-
STEP 2: Calculate the length of the declared array.
-
STEP 3: Loop through the array by initializing the value of variable "i" to 1 (because first even positioned element lies on i = 1) then incrementing its value by 2, i.e., i=i+2.
-
STEP 4: Print the elements present in even positions.
#Initialize array
arr = [1, 2, 3, 4, 5];
print("Elements of given array present on even position: ");
#Loop through the array by incrementing the value of i by 2
#Here, i will start from 1 as first even positioned element is present at position 1.
for i in range(1, len(arr), 2):
print(arr[i]);
8) Python program to print the elements of an array present on odd position
In this program, we need to print the elements of the array which are present in odd positions. This can be accomplished by looping through the array and printing the elements of an array by incrementing i by 2 till the end of the array is reached.
In the above array, the elements present on odd positions are a, c and e.
ALGORITHM:
-
STEP 1: Declare and initialize an array.
-
STEP 2: Calculate the length of the declared array.
-
STEP 3: Loop through the array by initializing the value of variable "i" to 0 then incrementing its value by 2, i.e., i=i+2.
-
STEP 4: Print the elements present in odd positions.
#Initialize array
arr = [1, 2, 3, 4, 5];
print("Elements of given array present on odd position: ");
#Loop through the array by incrementing the value of i by 2
for i in range(0, len(arr), 2):
print(arr[i]);
}