Within a program SwappingPairsjava write a method called swa

Within a program SwappingPairs.java, write a method called swapPairs that accepts an array of integers and swaps the elements at adjacent indexes. That is, elements 0 and 1 are swapped, elements 2 and 3 are swapped, and so on. If the array has an odd length, the final element should be left unmodified. Your main method should create test arrays and call the swapPairs method.

For example, the array [10, 20, 30, 40, 50] should become [20, 10, 40, 30, 50] after a call to your method.

Solution

SwappingPairs.java

import java.util.Arrays;


public class SwappingPairs {

  
   public static void main(String[] args) {
       int a[] = {10, 20, 30, 40, 50};
       swapPairs(a);
       System.out.println(Arrays.toString(a));
       int b[] = {10, 20, 30, 40, 50,60};
       swapPairs(b);
       System.out.println(Arrays.toString(b));
  

   }
   public static void swapPairs(int a[]){
       int temp = 0;
       for(int i=0; i<a.length-1; i=i+2){
           temp = a[i+1];
           a[i+1] =a[i];
           a[i] = temp;
       }
   }

}

Output:

[20, 10, 40, 30, 50]
[20, 10, 40, 30, 60, 50]

Within a program SwappingPairs.java, write a method called swapPairs that accepts an array of integers and swaps the elements at adjacent indexes. That is, elem

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site