Python program that uses a for loop and the modulus operator to print the elements of an array that are present on odd positions:

Created with Sketch.

Python program that uses a for loop and the modulus operator to print the elements of an array that are present on odd positions:

def print_odd_elements(arr):
    for i in range(len(arr)):
        if i % 2 != 0:
            print(arr[i])

# Example usage
arr = [1, 2, 3, 4, 5]
print_odd_elements(arr)

The function print_odd_elements(arr) takes an array as an argument. It uses a for loop to iterate over the indices of the array, using the range() function to generate a range of indices from 0 to len(arr). For each index, it checks if the index is odd using the modulus operator (%), if the remainder of index divided by 2 is not 0, the index is odd. If the index is odd, it prints the element at that index in the array.

The example usage creates an array and calls the print_odd_elements() function to print the elements of the array that are present on odd positions.

You could also use slicing and negative indexing to print the elements of an array present on odd positions

def print_odd_elements(arr):
    print(*arr[1::2])

This method uses slicing and negative indexing to access the elements present on odd positions by starting from the index 1 and then it uses the * operator to unpack the elements and pass them as separate positional arguments to the print() function.

Leave a Reply

Your email address will not be published. Required fields are marked *