Javatpoint Logo
Javatpoint Logo

Reverse an Array in C++

This section will discuss the different ways to reverse an array in the C++ programming language. The reverse of an array means to change the order of the given array's elements. This technique reverses the last element of the array into the first one, and the first element becomes the last. However, the process continues until all characters or elements of the array are completely reversed.

For example, the array contains elements like 'H', 'E', 'L', 'L', 'O', and when we reverse all the elements of an array, it returns the inverted array as 'O', 'L', 'L', 'E', 'H'. So, this way, all the characters in the array are reversed.

Reverse an Array in C++

Different ways to reverse an array

Following are the various ways to get the reverse array in the C++ programming language.

  • Reverse an array using for loop
  • Reverse an array using the reverse() function
  • Reverse an array using the user-defined function
  • Reverse an array using the pointers
  • Reverse an array using the Recursion function

Program to reverse an array using the for loop

Let's create a program to reverse the elements of the array using for loop in C++.

Program1.cpp

Output

Please, enter the total no. you want to enter: 6
 Enter the element 1: 78
 Enter the element 2: 12
 Enter the element 3: 54
 Enter the element 4: 24
 Enter the element 5: 7
 Enter the element 6: 90

 Reverse all elements of the array:
90 7 24 54 12 78

Program to reverse an array using the reverse() function

Let's consider an example to print the reverse of an array using the reverse () function in C++.

Program2.cpp

Output

2 5 90 21 78 34

Program to reverse an array using the user-defined function

Let's consider an example to display the reverse of array elements using the user-defined in C++.

Program3.cpp

Output

Number of elements to be entered:
7
 Enter the array elements:
45
32
89
21
78
34
65
 Elements are:
45 32 89 21 78 34 65
 The reverse of the given array is:
65 34 78 21 89 32 45

Program to reverse an array using the pointer

Let's consider an example to demonstrate the reversing of the array elements using the pointers in C++.

Program4.cpp

Output

No. of array elements to be entered:
6
 Enter the elements: 45
32
89
63
4
6
 Entered elements of the array are:

        45      32      89      63      4       6
 The reversed array elements are:

         6
         4
         63
         89
         32
         45

Reverse an array using the Recursion function

Let's create a program to reverse the array elements using the recursion function in C++.

Program5.cpp

Output

Original elements of the arrays
20 34 5 8 1 78
 Reverse elements of the array are:
78 1 8 5 34 20

Next TopicC++ date and time





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA