# Swap Kth Element from Beginning with Kth element from end

Swap Kth Element from Beginning with Kth element from end” is a basic problem of array data structure. Here, we are given an array of size ‘n’ and our task is to swap kth element from beginning with kth element from end, where (k<=n).

Example (Swap Kth Element from Beginning with Kth element from end):

```INPUT:
Arr = {11, 22, 33, 44, 55, 66, 77, 88, 99}
K = 4
OUTPUT:
Arr = {11, 22, 33, 66, 55, 44, 77, 88, 99}```

The steps required to swap kth element from beginning with kth element from end are as follows:

1. Scan the size of array.
2. Scan array elements.
3. Swap (k-1)th element with (n-k-1)th.
4. Print the resultant array.

#### C++ Program swap kth element from beginning with kth element from end is as follows:

```/* Program to swap kth element from beginning with kth element from end */
#include<bits/stdc++.h>
using namespace std;
int main()
{
/* Scan array size */
int n;
cout<<"Enter array size: ";
cin>>n;

/* Scan array elements */
int arr[n];
cout<<"\nEnter array elements:";
for(int i = 0; i < n; i++)
cin>>arr[i];

/* Scan Kth Number */
int k;
cout<<"\nEnter kth number:";
cin>>k;

/* Printing array before swapping */
cout<<"\nArray before swapping:\n";
for(int i = 0; i < n; i++)
cout<<arr[i]<<" ";

/* Swap the number */
int temp = arr[k-1];
arr[k-1] = arr[n-k];
arr[n-k] = temp;

/* Printing array after swapping */
cout<<"\nArray after swapping:\n";
for(int i = 0; i < n; i++)
cout<<arr[i]<<" ";
}
```
```OUTPUT:
Enter array size: 9
Enter array elements:
11 22 33 44 55 66 77 88 99
Enter kth number: 9
Array before swapping:
11 22 33 44 55 66 77 88 99
Array after swapping:
99 22 33 44 55 66 77 88 11

Time Complexity:
O(1), for swapping numbers```

Related Posts: