Python program that uses a for loop to print the elements of an array in reverse order:

Created with Sketch.

Python program that uses a for loop to print the elements of an array in reverse order:

def print_array_reverse(arr):
    for i in range(len(arr) - 1, -1, -1):
        print(arr[i])

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

The function print_array_reverse(arr) takes an array as an argument. It uses a for loop to iterate over the indices of the array in reverse order, starting from the last index and ending at the first index. It uses the range() function to generate a range of indices from len(arr) - 1 to -1 with a step of -1. For each index, it prints the element at that index in the array.

The example usage creates an array and calls the print_array_reverse() function to print the elements of the array in reverse order.

You could also use negative indexing to access the elements of an array in reverse order and the for loop to iterate over the array.

def print_array_reverse(arr):
    for i in arr[::-1]:
        print(i)

This method uses negative indexing to access the elements of the array in reverse order and then use a for loop to iterate over the reversed array.

Another alternative way is to use reversed() function with the for loop.

 
def print_array_reverse(arr):
    for i in reversed(arr):
        print(i)

This method uses reversed() function to reverse the elements of the array and then use a for loop to iterate over the reversed array.

Leave a Reply

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