C++ Program to swap adjacent elements of an array


In this program, You will learn how to swap adjacent elements of an array in C++.


List is: 1, 2, 3, 4, 5, 6

After swap: 2, 1, 4, 3, 6, 5


Example: How to swap adjacent elements of an array in C++

Run it Now
#include<iostream>
using namespace std;

int main() {

    int i, t, num, arr[100];

    cout << "Enter Array Size :";
    cin>>num;

    cout << "\nEnter Numbers :";
    for (i = 0; i < num; i++) {
        cin >> arr[i];
    }
    i = 0;
    while (i < num - 1) {
        t = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = t;
        i = i + 2;
    }

    cout << "\nArray List after Swapping :";
    for (i = 0; i < num; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Output:

Enter Array Size :6
Enter Numbers :1 2 3 4 5 6
Array List after Swapping :2 1 4 3 6 5