Python Program to Print the Elements of an Array Present on Odd Positions

Python Program to Print the Elements of an Array Present on Odd Positions

Arrays, also known as lists in Python, are versatile data structures used to store multiple items. One common task is accessing elements based on their positions within the array, especially when you need to focus on specific indices like odd or even positions. In this blog post, we'll cover how to print the elements of an array that are located at odd positions.

Problem Statement
Given an array, print the elements that are present at odd positions. In programming, array indexing usually starts at 0, which means positions 1, 3, 5, etc., are considered odd positions.
For example, if the array is [10, 20, 30, 40, 50], the output should be 20, 40 since these are the elements at odd indices (1, 3).

Approach
To achieve this:
1. Loop through the array using a for loop with an index.
2. Use the modulo operator (%) to check if the index is odd.
3. If the index is odd, print the corresponding element.

Python Code
Here's a Python program that prints the elements of an array located at odd positions:
# Python program to print elements of an array at odd positions
# Initialize the array
array = [10, 20, 30, 40, 50, 60]
# Print a message indicating the elements at odd positions
print("Elements at odd positions:")
# Iterate through the array using the index
for i in range(len(array)):
    # Check if the position is odd
    if i % 2 != 0:
        print(array[i], end=' ')

Output
Elements at odd positions:
20 40 60

Explanation of the Code
1. Initialization: The array is initialized with some values, e.g., [10, 20, 30, 40, 50, 60].
2. Iteration with Index: The for loop iterates through each index of the array using range(len(array)), which covers all indices.
3. Checking Odd Index: The condition if i % 2 != 0 checks whether the index is odd. If true, the corresponding element is printed.

This is the screenshot of the Jupyter Notebook of the Above Program

Conclusion
Accessing elements based on specific positions is a basic yet essential skill in programming. The method shown above demonstrates how to print elements from odd positions

Comments