Write a program to reverse an array or string in C++

C++Server Side ProgrammingProgramming

Here, we are given an array or a string of characters. We will create a program to reverse the elements of an array or string.

Let’s take an example to understand the problem,

Input

array = {2, 5, 7, 1, 9}

Output

{9, 1, 7, 5, 2}

Input

string = “Hello!”

Output

!0lleH

To create a program, we will loop through the elements of the array/string(both work in the same way). Taking one variable for start and one of end. And swap both elements. Increment the start variable and decrement the end variable. The swapping will continue till start variable’s value is less than end variable.

The program can be created in two ways, one is iterative and the other is recursive. We will create program that will demonstrate the working of both methods.

Example

Method 1: Iterative approach

 Live Demo

Program :
#include <iostream>
using namespace std;
void revereseArrayIt(int arr[], int start, int end){
   while (start < end){
      int temp = arr[start];
      arr[start] = arr[end];
      arr[end] = temp;
      start++;
      end--;
   }
}
int main() {
   int arr[] = {6, 9, 1, 4, 0, 5};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"Orignal Array : ";
   for (int i = 0; i < n; i++)
      cout<<arr[i]<<" ";
   cout<<endl;
      revereseArrayIt(arr, 0, n-1);
      cout << "Reversed array : ";
      for (int i = 0; i < n; i++)
         cout<<arr[i]<<" ";
   cout<<endl;
   return 0;
}

Output

Orignal Array : 6 9 1 4 0 5
Reversed array : 5 0 4 1 9 6

Example

Method 2 : Recursive Approach

 Live Demo

#include <iostream>
using namespace std;
void revereseArrayRec(int arr[], int start, int end){
   if(start >= end)
      return;
   int temp = arr[start];
   arr[start] = arr[end];
   arr[end] = temp;
   revereseArrayRec(arr,start+1, end-1);
}
int main() {
   int arr[] = {6, 9, 1, 4, 0, 5};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"Orignal Array : ";
   for (int i = 0; i < n; i++)
      cout<<arr[i]<<" ";
   cout<<endl;
      revereseArrayRec(arr, 0, n-1);
      cout << "Reversed array : ";
      for (int i = 0; i < n; i++)
         cout<<arr[i]<<" ";
   cout<<endl;
   return 0;
}

Output

Orignal Array : 6 9 1 4 0 5
Reversed array : 5 0 4 1 9 6
raja
Published on 20-Apr-2020 14:42:44
Advertisements