Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reverse of array in c++

int main()
{
    int num[5];
    int num2[5];
    int n;
    int j = 0;
    cout << "provide size of array" << endl;
    cin >> n;
    for(int i =0; i< n; i++){
        cin >> num[i];
    }
    cout << "the size of n is " << n << endl;
    while(n != 0){
        num2[j] = num[n-1];
        n--;
        j++;
    }
    for(int k = 0; k< 5; k++){
        cout << num2[k] << endl;
    }
}

I need to create program for reversing the array, but without swap, I have done this but this is an optimal way or using swap() is optimal ? as in swap I don’t required to create another array.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you cannot use swap, you could use addition and subtraction instead

#include <array>
#include <iostream>

void reverse( int* arr, unsigned n ) {
    if ( n==0 ) return;
    unsigned i=0;
    unsigned j=n-1;
    for ( ; i<j; i++,j-- ) {
        arr[i] = arr[i] + arr[j];
        arr[j] = arr[i] - arr[j];
        arr[i] = arr[i] - arr[j];
    }
}

int main() {
    std::array<int,5> values{1,2,3,4,5};
    reverse( &values[0], values.size() );
    for ( int val : values ) {
        std::cout << val << " ";
    }
    return 0;
}

Code: https://godbolt.org/z/MrW8cEzPs

Result:

Program returned: 0
Program stdout

5 4 3 2 1 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading