Reverse an array(list) using while loop Python


Problem Statement

Our program will first take the input of array (list) size and then the elements of the array (list) by the user. After applying some logic it will return the reverse of the input array (list).

[elementor-template id=”5253″]

For example:
Case 1: if the user inputs 4 as array (list) size and the array (list) elements as 1,2,3,4.

        The output should be 4,3,2,1.

Case 2: if the user inputs 5 as array (list) size and the array (list) elements as 9,8,7,6,5.

         The output should be 5,6,7,8,9.

Algorithm to print an array(list) in reverse order using while loop

Step 1: Start

Step 2: take an input from the user (let’s say size).

Step 3: Create two empty lists.

Step 4: Add elements to the list

Step 5:

 startIndex = 0;

lastIndex = size – 1;

while lastIndex >= 0:

                        revArr.append(arr[lastIndex])

                         startIndex+=1

                        lastIndex-=1 

Step 6: Print reversed list i.e. revArr

Step 7: Stop

[elementor-template id=”5257″]

Following is sample Python code.


# taking the input from the user to fix the array size
size=int(input("Enter the number of elements you want in array: "))
# Create two empty lists
arr=[]
revArr=[]
# adding the elements to the list
for i in range(0,size):
    elem=int(input("Please give value for index "+str(i)+": "))
    arr.append(elem)
startIndex = 0;
lastIndex = size - 1;
# iterate the while loop till the lastindex 0
while (lastIndex>=0):
    revArr.append(arr[lastIndex])
    startIndex+=1
    lastIndex-=1
# printing the reversed list
print("Array in reverse order")
for i in range(0,size):     
    print(revArr[i],end=' ')