Coders Packet

CPP-Reverse of an array (C++)

By Raunak Chhabra

In this we'll use C++ to reverse an array. We'll take the user input to number of array elements and elements as well.

#include
using namespace std;

void reversearray(int arr[], int start, int end){
    while(start<end){
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}
void printarray(int a[],int n){
        for(int i=0;i<n;i++){
             cout<<a[i]<<endl;
        } 
        
    
}    
 
int main(){
    int n;
    cin>>n;
    int a[1000];
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    reversearray(a,0,n-1);
    printarray(a,n);
   } 

    

In this we started of with creating a function to reverse an array first, it would take the name of array, its start and end as a argument. And now how we use to take another variable to swap 2 numbers, similarly we'll do it here, but instead we'll do start++ end--, so that it keeps changing and reversing from start and end of the array. The next step is to print the array, so we created another function as well here. Int main has now the array limit to 1000, we'll now take user input and reverse it by calling the reversearray function and printing using print function we created.

Download project

Reviews Report

Submitted by Raunak Chhabra (raunakchhabra)

Download packets of source code on Coders Packet