Input: 15 7 18 21 9 12 87 25 8 5
output: 7 15 21 18 12 9 25 87 5 87
Apply swap logic for every odd position element and even position element of an array. but no need to think about the total no of elements of the array. It may be even numbers of elements or odd numbers of elements
class OddEvenExchange { public static void main() { int []arr={15,7,18,21,9,12,87,25,8,5}; int i,temp; System.out.println("\nAfter Exchange"); for(i=0;i<arr.length;i++) { System.out.print(arr[i] + " "); } for(i=0;i<arr.length;i+=2) { temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } System.out.println("\nBefore Exchange"); for(i=0;i<arr.length;i++) { System.out.print(arr[i] + " "); } } }