Python program that uses a for loop and the modulus operator to print the elements of an array that are present on even 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 even positions:

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

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

The function print_even_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 even using the modulus operator (%), if the remainder of index divided by 2 is 0, the index is even. If the index is even, it prints the element at that index in the array.

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

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

def print_even_elements(arr):
    print(*arr[::2])

This method uses slicing and negative indexing to access the elements present on even positions 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 *