Java Program to swap adjacent elements of an array

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


import java.util.Scanner;

class Main {
    public static void main(String args[]) {
       //Statement
   }
}

Java Program to swap adjacent elements of an array

Example: How to swap adjacent elements of an array in Java

import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int i, t;
        int arr[] = new int[6];

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter 6 numbers:");

        for (i = 0; i < 6; i++) {
            arr[i] = sc.nextInt();
        }

        i = 0;
        while (i < 6 - 1) {
            t = arr[i];
            arr[i] = arr[i + 1];
            arr[i + 1] = t;
            i = i + 2;
        }

        System.out.print("After swap list are:");
        for (i = 0; i < 6; i++) {
            System.out.print(" " + arr[i]);
        }

    }
}

Output:

Enter 6 numbers:10 20 30 40 50 60
After swap list are: 20 10 40 30 60 50