215k views
5 votes
Write a program that reverses the elements of an array.

a) Fill the array with 10 random integers

User Lynvie
by
8.0k points

1 Answer

2 votes

Final answer:

The program in Python demonstrates reversing an array by first filling it with 10 random integers using the random module, and then reversing it using a function that employs slice notation.

Step-by-step explanation:

Writing a program to reverse an array involves creating an array with a set number of elements, filling it with random values, and then reversing the order of these elements. Here is an example program in Python that demonstrates this process:

import random

# Function to reverse the array
def reverse_array(arr):
return arr[::-1]

# Fill the array with 10 random integers
array = [random.randint(1, 100) for _ in range(10)]
print('Original array:', array)

# Reverse the array
reversed_array = reverse_array(array)
print('Reversed array:', reversed_array)

This program first imports the random module, which is necessary for generating random numbers. It defines a function reverse_array that takes an array as an argument and returns a reversed version of that array using Python's slice notation. The randint function is used within a list comprehension to fill an array with ten random integers between 1 and 100. Finally, the program prints the original and reversed arrays to show the outcome.

User Volk
by
7.6k points