swap alternate in an array

1.5k views Asked by At

You have been given an array/list(ARR) of size N. You need to swap every pair of alternate elements in the array/list. You don't need to print or return anything, just change in the input array itself.

#include <iostream>;
using namespace std;

void printArr(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i]<<i;
}

void UpdateArr(int arr[], int n)
{

   int i = 0, j = n - 1;

    
    while (i < j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        i += 2;
        j -= 2;
    }
  cout<<' printArr(arr[], n)';
}

int main()
{
    int t;
    cin>> t;

     int n;
 cin>> n;
 int input[100];
 for(int i=0; i<n; i++) {
    cin >>input[i];
 }
    int arr[100] ;
    n = sizeof(arr) / sizeof(arr[0]);

    UpdateArr(arr, n);

    return 0;
}

1

There are 1 answers

0
Aybak On

I'm not sure what are you exactly expecting the output to be (pls edit it and show the expected output) but I think this is what you need to do

#include <iostream>
#include <iomanip>
using namespace std;

void UpdateArray(int Arr[], size_t n) {
    for (size_t i = 0; i < n / 2; i++) {
        int Holder = Arr[i];
        Arr[i] = Arr[~i + n];
        Arr[~i + n] = Holder; } }

int main() {
    int Arr[7] = { 1,2,3,4,5,6,7 };
    UpdateArray(Arr, 7);
    for (int i = 0; i < 7; i++) {
        std::cout << Arr[i] << "\n"; }
    return 0; }

size_t is like an int but it can't go into negative, but it can take bigger positive numbers, you can replace it with int, it shouldn't make a difference.
so we loop through half the array, replacing first items with last, the [~i + n] flips the value to the other side, so like index 4 in a array size of 20 will become 15