5) Python program to print the elements of an array
This is a simple program to create an array and then to print it's all elements.
Now, just know about arrays.
Arrays are the special variables that store multiple values under the same name in the contiguous memory allocation. Elements of the array can be accessed through their indexes.
1 2 3 4 5
Here, 1, 2, 3, 4 and 5 represent the elements of the array. These elements can be accessed through their corresponding indexes, 1.e., 0, 1, 2, 3 and 4.
ALGORITHM:
-
STEP 1: Declare and initialize an array.
-
STEP 2: Loop through the array by incrementing the value of i.
-
STEP 3: Finally, print out each element of the array.
#Initialize array
arr = [1, 2, 3, 4, 5];
print("Elements of given array: ");
#Loop through the array by incrementing the value of i
for i in range(0, len(arr)):
print(arr[i]),
6) Python program to print the elements of an array in reverse order
In this program, we need to print the elements of the array in reverse order that is; the last element should be displayed first, followed by second last element and so on.
ALGORITHM:
-
STEP 1: Declare and initialize an array.
-
STEP 2: Loop through the array in reverse order that is, the loop will start from (length of the array - 1) and end at 0 by decreasing the value of i by 1.
-
STEP 3: Print the element arr[i] in each iteration.
#Initialize array
arr = [1, 2, 3, 4, 5];
print("Original array: ");
for i in range(0, len(arr)):
print(arr[i]),
print("Array in reverse order: ");
#Loop through the array in reverse order
for i in range(len(arr)-1, -1, -1):
print(arr[i]),