Python Program: Print Elements at Even Positions in an Array

In this blog post, we will delve into a Python program designed to print the elements of an array present at even positions. The article will walk through the algorithm used in the program, provide the Python code for implementation, and include examples with corresponding outputs.

Understanding the Algorithm

The algorithm for printing elements at even positions in an array involves the following steps:

1. Input Array: Accept an array of elements, either predefined or entered by the user.
2. Traverse Array: Iterate through the array and identify elements at even positions (indices).
3. Print Elements: Display the elements found at even positions.

Python Program for Printing Elements at Even Positions

Let’s implement the algorithm in a Python program:

``````def print_even_position_elements(arr):
print("Elements at Even Positions:")
for i in range(len(arr)):
if i % 2 == 0:
print(arr[i])

# Example array
example_array = [10, 20, 30, 40, 50, 60, 70, 80]

# Print even position elements
print_even_position_elements(example_array)
``````

Output Example

Example: Printing Even Position Elements in `[10, 20, 30, 40, 50, 60, 70, 80]`

``````Elements at Even Positions:
10
30
50
70
``````

Explanation

The Python program defines a function `print_even_position_elements` that takes an array as input. It uses a `for` loop to iterate through the array, and the `if` statement checks whether the current index is even (`i % 2 == 0`). If true, it prints the element at that position.

Conclusion

This Python program offers a straightforward way to extract and display elements at even positions in an array. Understanding array traversal and index manipulation is essential in various programming scenarios. You can use this program as a foundation for more complex array-related tasks or adapt it based on specific requirements. Feel free to experiment with different arrays and explore variations of the algorithm. If you have any questions or would like to explore more Python programming topics, please feel free to ask!