Home > Back-end >  Reverse of array in c
Reverse of array in c

Time:12-25

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.

CodePudding user response:

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 
  • Related