-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathArray_Swap_Alternate_Elements
More file actions
37 lines (31 loc) · 1 KB
/
Array_Swap_Alternate_Elements
File metadata and controls
37 lines (31 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
Problem Description: You are given with an array of length N, you have to swap every pair of
alternate elements in the array.
For example:N= 6
arr[] = 9 3 6 12 4 78
Output after swapping : 3 9 12 6 78 4
*/
import java.util.Scanner;
public class SwapAlternate {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Size of Array: ");
int n = in.nextInt();
// Input Array Elements
int arr[] = new int[n];
System.out.println("Enter " +n+ " Array Elements: ");
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
// Logic to Swap Alternate Elements
for (int i = 0; i < (arr.length - 1); i += 2) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
// Print/Output updated new Array with alternate elements swapped
for (int j = 0; j < n; j++) {
System.out.print(arr[j]+ " ");
}
}
}