Program Of Reversing Array Using C++

Reverse Array

Array is defined as a contiguous block of memory which allocates similar type of data. In Array indexing starts with 0 and ends with -1.

In reverse array , we traverse elements from end to start.

Array v/s String in C

How to Reverse An Array in C++ :

In general, Array can be reversed without using in-built method is loop. By using loop we can reverse the array easily.

Below are the two techniques to reverse the array using for loop :

Method 1 :

In the below program, we traverse the string using for loop from back and print the particular character of the string to get the reverse string.

Run
#include<bits/stdc++.h>
using namespace std;

int main(){
    vector< int > arr;
    arr.push_back(10);
    arr.push_back(20);
    arr.push_back(30);
    arr.push_back(40);
    arr.push_back(50);
    int n = arr.size();
    for(int i=0;i< n/2;i++){
        swap(arr[i], arr[n-i-1]);
    }
    cout<<"The reverse array is : ";
    for(int i=0;i< n;i++){
        cout<< arr[i]<< " ";
    }
}

Output :

The reverse array is : 50 40 30 20 10

In the below program, we traverse the string using for loop from start and print the particular character of the string to get the reverse string by using [n-i] to get the particular character from back

Method 2:

Run
#include<bits/stdc++.h>
using namespace std;
void disp (int arr1[], int num)
{
  int i;
  for (i = 0; i < num; i++)
    {
      cout << arr1[i] << " ";
    }
}
void reverse (int arr1[], int num)
{
  reverse (arr1, arr1 + num);
}
int main ()
{
  int arr1[] = { 1, 2, 3, 4, 5, 6, 7 };
  int num = sizeof (arr1) / sizeof (arr1[0]);
  reverse (arr1, num);
  disp (arr1, num);
  return 0;
}

Output :

7 6 5 4 3 2 1 

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription