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++.

#include<iostream>
using namespace std;

int main() {

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

    cout << "Enter array size:";
    cin>>num;

    cout << "Enter 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 << "Array List after Swapping:";
    for (i = 0; i < num; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Output:

Enter array size:6
Enter numbers:10 20 30 40 50 60
Array List after Swapping:20 10 40 30 60 50 

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.