reverse array in cpp | AsgarTech


Reversing Arrays in C++: A Comprehensive Guide


Introduction


Reversing an array is a fundamental programming task that involves rearranging the elements of an array in reverse order. In C++, there are several effective methods to achieve this, each with its own advantages and considerations. This blog post will guide you through these techniques, providing clear explanations and code examples.


Methods for Reversing Array:


Iterating from Both Ends:


#include <bits/stdc++.h>

using namespace std;


void f(int n ,int arr[] ,int i){

    if(i >= n/2) return;

    swap(arr[i] , arr[n-i-1]);

    f(n,arr,i+1);

}


int main() {

int n = 5;

int arr[5] = {1,2,3,4,5};

f(n, arr ,0);

for(int i = 0 ; i<n;i++){

    cout<<arr[i]<<endl;

}


    return 0;

}


output:

5

4

3

2

1

No comments: